﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using WP.Commons;
using WP.DB;
using WP.Modules;
using WP.Controls;
using WP.Controls.GridColumn;

using WP.RM.BusinessRule;
using WP.RM.BusinessLogical;
using WP.RM.DataAccess;

namespace WP.RM.Form
{
    public partial class frmRMProductBOMRevMtn : BaseMtn 
    {
        public frmRMProductBOMRevMtn()
        {
            InitializeComponent();
            LoadAllControl(new ArrayList(this.Controls));
            this.MtnTabControl = this.tbcMain;
            this.DesignTabsName = "tbpGeneral";
            tbcMain.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.MinimumSize = this.Size;
        }

        #region Define Variable
        private bool mblnSettingStatus = false;
        private bool[] mDtlColumnReadOnlyArray;
        private bool[] mDtlColumnReadOnlyArray_LabourCost;
        private bool m_bCanTrigerCellValueChangedEven = false;
        private bool m_bCanTrigerCellValueChangedEven_LabourCost = false;
        private bool m_bSettingStatus = false;
        private bool m_bDtlChanged = false;
        private bool m_bDtlChanged_LabourCost = false;
        private string mstrWhereCondition = "";
        private frmWKParameter frmParameter = null ; 
        private System.Windows.Forms.DataGridView.HitTestInfo mhtiDtl = null;
        private DBAccess mdbcon = new DBAccess(false, false);
        private enum DtlCol
        {
            RowSeqNo = 0,
            SeqNo,
            VersionNo,
            ProductFItemID,
            ProductName,         
            WKID,
            WKName,
            WKRemark,
            IsKeyWK,
            IsInputWK,
            CategoryID,
            CategoryName,
            SetID,
            SetName,
            FItemID,
            ItemNo,
            ItemName,
            SupNo,
            SupName,
            Price,
            PriceUnit,
            Qty,         //定额数量
            WastageRate, //损耗率 
            QtyWastage,  //损耗数量
            DetailCost,  //定额成本
            LabourCost,  //人工成本
            TotalCost,   //总成本    
            TechnicsName,
            RecID,
            ValueChanged,
            DelButton
        }

        private enum LabourCostCol
        {
            RowSeqNo = 0,
            BOMSeqNo,
            SeqNo,
            WKID,
            WKName,
            /// <summary>
            /// 工价类别
            /// </summary>
            WKPriceType,
            WKRemark,
            IsKeyWK,
            /// <summary>
            /// 工序产出
            /// </summary>
            WKOutName,
            CategoryID,
            CategoryName,
            SetID,
            SetName,
            VersionNo,
            ProductFItemID,
            ProductName,
            FItemID,
            /// <summary>
            /// 主要是用来计算这个工序要做的工作总量
            /// </summary>
            ItemNo,      
            ItemName,
            CalUnit,
            /// <summary>
            /// 分切方式
            /// </summary>
            CutType,
            /// <summary>
            ///      //总数量
            /// </summary>
            WorkQty,
            /// <summary>
            /// //总加工计量数量( = WorkQty/ CutType )
            /// </summary>
            TotalQty,    
            /// <summary>
            /// //10小时额定产量
            /// </summary>
            StandardQty, 
            /// <summary>
            /// //预计用工时间
            /// </summary>
            UsedHours,   
            /// <summary>
            /// // 固定工资
            /// </summary>
            StandardWage,  
            /// <summary>
            ///  //26天标准工资
            /// </summary>
            StandardWage26,
            /// <summary>
            ///  //记件工价
            /// </summary>
            UnitCost,
            /// <summary>
            /// 计件工资
            /// </summary>
            TotUnitCost,         
            /// <summary>
            /// 人工成本 = 总工价*数量 //总工价来自于工时费用标准 TotUnitCost
            /// </summary>
            DtlLaborTotCost,
            /// <summary>
            /// //工时费用标准
            /// </summary>
            WorkCost,    
            /// <summary>
            /// //工时费用
            /// </summary>
            TotWorkCost,  
            /// <summary>
            ///   //备注
            /// </summary>
            Remark,     
            /// <summary>
            /// 工艺名称
            /// </summary>
            TechnicsName,

            RecID,
            ValueChanged,
            DelButton
        }

        #endregion

        private enum MtnType
        {
            isRev=0,
            isSales=1,
        }

        private MtnType mTypePara = new MtnType();

        #region ***Form Events

        private void frmRMProductBOMRevMtn_Load(object sender, EventArgs e)
        {
            mTypePara = MtnType.isRev;
            if (SysVar.CurrentMenuInfo.iParameter == 99) mTypePara = MtnType.isSales;
            if (mTypePara == MtnType.isRev)
            {
                this.TableName = "rmProductBOMRev";
                frmParameter = new frmWKParameter( frmWKParameter.FromType.ProductBOMRev );
            }
            else
            {
                this.TableName = "rmProductBOMSales";
                frmParameter = new frmWKParameter(frmWKParameter.FromType.ProductBOMSales);
            }
            //dgList.ColumnWidth = "0,70,180,100,40,20,120,90,130";
            dgList.ConnectionString = DBAccess.ConnectionDBString;
            dgList.TableName = this.TableName;
            dgList.ColumnWidth = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgList.Name);
            string strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            dgList.Sql = strSql;
            this.formStatus = FormStatus.Query;
            InitGridDtl();
            FillLookUpInfo();
            ShowOverViewGrid((this.CurrentMenuInfo.strOverViewCondition != "" && this.CurrentMenuInfo.strOverViewCondition != null ? " Where " : "") + this.CurrentMenuInfo.strOverViewCondition);

            frmParameter.TopMost = true;
            frmParameter.TopLevel = false;
            frmParameter.Dock = DockStyle.Fill;
            frmParameter.FormBorderStyle = FormBorderStyle.None;
            frmParameter.Show();
            pnlParameter.Controls.Add(frmParameter);

            FillTree();
        }

        private void InitBOMHdr()
        {
            DBAccess dbcon = new DBAccess(false, false);
            
            try
            {
                string strSQL = "select * from rmProductBOMHdr where CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}'";
                strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtTechnicsName.Text);
                DataRow drRow = dbcon.GetDataFirstRow(strSQL);
                if (drRow != null)
                {
                    dbcon.BeginTran();                    
                    if (mTypePara == MtnType.isRev)
                    {
                        RMProductBOMRevBRL rmBRL = new RMProductBOMRevBRL();
                        if (rmBRL.InitProductBOMRev(dbcon, drRow, txtProductFItemID.Text, txtCategoryID.Text, txtSetID.Text, txtTechnicsName.Text, txtVersionNo.Text))
                            dbcon.CommitTran();
                        else
                            dbcon.RollbackTran(); ;
                    }
                    else
                    {
                        RMProductBOMSalesBRL rmBRL = new RMProductBOMSalesBRL();
                        if (rmBRL.InitProductBOMRev(dbcon, drRow, txtProductFItemID.Text, txtCategoryID.Text, txtSetID.Text, txtTechnicsName.Text, txtVersionNo.Text))
                            dbcon.CommitTran();
                        else
                            dbcon.RollbackTran(); ;
                    }

                }
                if (!UpdateData()) return;  
            }
            catch (Exception ex)
            {
                dbcon.RollbackTran();
            }
            dbcon.CloseCon();
        }

        private void ShowOverViewGrid()
        {
            ShowOverViewGrid("");
        }

        private void ShowOverViewGrid(string strWhereCondition)
        {
            string strSql = ""; string strOrderBy = "";
            if (dgList.Sql.Trim() == "")
                strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            else
                strSql = dgList.Sql;

            if (strWhereCondition != "")
            {
                strOrderBy = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartOrderBy);
                strSql = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartMain) + " " + strWhereCondition;
                //strSql += strOrderBy;
            }
            string strWhere = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartWhere);
            mstrWhereCondition = strWhere + ( strOrderBy ==""? "" : strOrderBy );
            this.dgList.Sql = strSql;
        }
        private void frmRMProductBOMRevMtn_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgList);
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvBOM);
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvLabourCost);
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
           
            if (!this.UpdateData()) return;
            base.SetStatusAfterUpdate();
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (this.ConfirmChange())
            {
                if (!this.UpdateData()) return;
            }
            this.formStatus = FormStatus.AddNew;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!this.DeleteData()) return;
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.formStatus = FormStatus.Delete;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
            {
                if (this.ConfirmChange())
                {
                    if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (!this.UpdateData()) return;
                    }
                }
            }
            this.ExitingStatus = true;
            this.Close();
        }
        private void btnHelp_Click(object sender, EventArgs e)
        {
            base.OnHelp();
        }
        private void btnToExcel_Click(object sender, EventArgs e)
        {
            if (this.tbcMain.SelectedTab == this.tbpOverview)
                base.ExportToExcel(dgList);
            else
            {
                  string strSQL = "";
                  if (mTypePara == MtnType.isRev)
                  {
                      strSQL = "select * from rmProductBOMRev where recid ='" + this.m_lRecId + "'";
                  }
                  else
                  {
                      strSQL = "select * from rmProductBOMSales where recid ='" + this.m_lRecId + "'";
                  }
                DataRow drHdr = mdbcon.GetDataFirstRow(strSQL);
                if (drHdr == null) return;
                BOMToExcel.ToExcel_BOM(mdbcon, BOMToExcel.BOMType.BOMRev , drHdr);
            }

        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Next);
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Prev);
        }
        private void btnTop_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Top);
        }
        private void btnBottom_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Bottom);
        }
        public override void SetNavigatorBarTooltip()
        {
            if (this.RecID <= 0)
            {
                this.btnBottom.ToolTipText = "定位到末页";
                this.btnTop.ToolTipText = "定位到首页";
                this.btnNext.ToolTipText = "定位到下一页";
                this.btnPrev.ToolTipText = "定位到前一页";
            }
            else
            {
                this.btnBottom.ToolTipText = "定位到末记录";
                this.btnTop.ToolTipText = "定位到首记录";
                this.btnNext.ToolTipText = "定位到下一条记录";
                this.btnPrev.ToolTipText = "定位到上一条记录";
            }
        }

        private void dgList_DefineColumn(object sender, EventArgs e)
        {
            base.SelectListViewField(dgList);
        }
        private void dgList_KeyDown(object sender, KeyEventArgs e)
        {
            if (this.tbcMain.SelectedTab == this.tbpOverview)
            {
                if (e.KeyCode == Keys.Enter && dgList.CurrentRow != null)
                {
                    this.RecID = Convert.ToInt64(dgList.RecID);
                }
            }
        }
        private void dgList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (dgList.CurrentRow != null && BaseFunctions.IsDataGridCell(this.dgList, e))
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
            if (CvtFunc.ToBoolean(utrVerClosed.Text == "Yes"))
            {
                Field_Change(utrVerClosed, new EventArgs());
                this.formStatus = FormStatus.Query;
            }
        }

        protected override void Field_Leave(object sender, System.EventArgs e)
        {
            base.Field_Leave(sender, e);
            Control con = sender as Control;
            if (con == null) return;
            //below is some speci field , need do some speci work
            if (con.Name == this.txtOtherCost.Name || con.Name == this.txtVersionCost.Name || con.Name == this.txtStartCost.Name)
            {
                txtStartCost.Text = BaseFunctions.FormatNumeric(txtStartCost.Text, "Ns.2");
                txtVersionCost.Text = BaseFunctions.FormatNumeric(txtVersionCost.Text, "Ns.2");
                txtOtherCost.Text = BaseFunctions.FormatNumeric(txtOtherCost.Text, "Ns.2");

                double dblQuantity = CvtFunc.ToDouble(DataFunctions.GetFieldValue(mdbcon, "rmProduct" , "Quantity", " productname='"+ txtProductName.Text  +"' "));

                txtVerUnitCost.Text = BaseFunctions.FormatNumeric((CvtFunc.ToDouble(txtTotalCostRev.Text) + CvtFunc.ToDouble(txtOtherCost.Text) + CvtFunc.ToDouble(txtVersionCost.Text) + CvtFunc.ToDouble(txtStartCost.Text)) / dblQuantity, "Ns.4");

            }
        }

 
        protected override void Field_Change(object sender, EventArgs e)
        {
            base.Field_Change(sender, e);
            if (this.formStatus == FormStatus.Delete) return;
            Control con = sender as Control;
            if (con == null) return;
            if (con.Name == utrVerClosed.Name)
            {
                if (CvtFunc.ToBoolean(con.Text))
                {
                    if (UpdateData())
                    {
                        this.formStatus = FormStatus.Query;
                        frmParameter.FillContent(this.m_lRecId.ToString());
                    }
                }
                else
                {
                    if (this.formStatus == FormStatus.Query)
                    {
                        //this.formStatus = FormStatus.Update;
                        
                    }
                    frmParameter.FillContent(this.m_lRecId.ToString());
                }
            }
            else if (con.Name == txtProductName.Name && this.formStatus == FormStatus.AddNew)
            {
                if (mTypePara == MtnType.isRev)
                {
                    txtVersionNo.Text = CvtFunc.ToString(CvtFunc.ToInt(DataFunctions.GetFieldValue("rmProductBOMRev", "max(VersionNo)", "productname='" + txtProductName.Text + "'")) + 1);
                }
                else if ( mTypePara == MtnType.isSales) 
                {
                    txtVersionNo.Text = CvtFunc.ToString(CvtFunc.ToInt(DataFunctions.GetFieldValue("rmProductBOMSales", "max(VersionNo)", "productname='" + txtProductName.Text + "'")) + 1);
                }
            }
        }
        protected override void Field_KeyPress(object sender, KeyPressEventArgs e)
        {
            base.Field_KeyPress(sender, e);
        }
        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) //激活回车键
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            if (!(msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN))
            {
                return false;
            }

            bool blnRet = false;
            if (BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvBOM.Name))
            {
                blnRet = dgvBOM_KeyDownEvent(keyData);
            }
            else if (BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvLabourCost.Name))
            {
                blnRet = dgvLabourCost_KeyDownEvent(keyData);
            }
            if (!blnRet)
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }
            return blnRet;
        }
        private void tbcMain_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if ((this.formStatus == FormStatus.Query || this.formStatus == FormStatus.Delete) &&
                this.dgList.Rows.Count == 0 && e.TabPageIndex > 0)
            {
                e.Cancel = true;
                return;
            }

            if (e.TabPageIndex == 0)
            {
                if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
                {
                    if (this.ConfirmChange())
                    {
                        if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            if (!this.UpdateData())
                            {
                                if (m_bTabPageNeedCancel)
                                    e.Cancel = true;

                                m_bTabPageNeedCancel = true;
                                return;
                            }
                        }
                    }
                    this.formStatus = FormStatus.Delete;
                }
                else if (this.formStatus == FormStatus.Query)
                {
                    this.formStatus = FormStatus.Delete;
                }
                this.dgList.RefreshData();
                this.dgList.Focus();
            }
            else if (e.TabPageIndex != 0 && this.formStatus != FormStatus.AddNew)
            {
                if (this.RecID == -1)
                    this.RecID = Convert.ToInt64(dgList.RecID);

                if (e.TabPage == tbpOtherCost && (this.dgvBOM.CurrentRow == null || CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) == ""))
                {
                    this.tbcMain.SelectedTab = tbpBOM;
                }
            }
            else if (e.TabPageIndex == 2  && this.formStatus == FormStatus.AddNew)
            {
                if (this.formStatus == FormStatus.AddNew)
                {
                    if (!this.UpdateData()) return;
                    FillGrid();
  
                }
            }
            else if ((e.TabPage == tbpBOM || e.TabPage == tbpOtherCost) && this.formStatus == FormStatus.AddNew)
            {
                if (!this.UpdateData()) return;
                FillGrid();
            }
            if (e.TabPage == tbpGeneral && this.formStatus == FormStatus.Update)
            {
                if (!this.UpdateData()) e.Cancel = true ;
                FillHdrData(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtVersionNo.Text, txtTechnicsName.Text);    
                
            }
            if (e.TabPageIndex == 0)
            {
                btnCondition.Enabled = true ;
                btnCopyToNewVer.Enabled = true;
            }
            else
            {
                btnCondition.Enabled = false;
                btnCopyToNewVer.Enabled = false;
            }
           
        }

        private void FillGrid()
        {
            FillDtl(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtVersionNo.Text);
            FillDtl_LabourCost(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtVersionNo.Text);
        }
        private void tbcMain_DrawItem(object sender, DrawItemEventArgs e)
        {
            BaseFunctions.TabControl_DrawItem(sender, e, true);
        }
        private void FileMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mnuItem = sender as ToolStripMenuItem;
            if (mnuItem != null)
            {
                switch (mnuItem.Name)
                {
                    case "newToolStripMenuItem":
                        btnNew_Click(sender, e);
                        break;
                    case "cancelToolStripMenuItem":
                        btnCancel_Click(sender, e);
                        break;
                    case "deleteToolStripMenuItem":
                        btnDelete_Click(sender, e);
                        break;
                    case "saveToolStripMenuItem":
                        btnUpdate_Click(sender, e);
                        break;
                    case "exitToolStripMenuItem":
                        btnExit_Click(sender, e);
                        break;
                }
            }
        }

        #endregion Form Events***

        #region ***Form Functions

        public override bool UpdateData()
        {
            if (this.formStatus == FormStatus.Query) return true;
            bool bUpdateResult = true;
            bool blnNeedInitProductRev = (this.formStatus == FormStatus.AddNew ? true : false);
            if (base.ConfirmChange())
            {
                string strVisionNo = "";
                if (blnNeedInitProductRev)
                {
                    strVisionNo = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue((mTypePara == MtnType.isRev ? "rmProductBOMRev" : "rmProductBOMSales"), "max(VersionNo)", "ProductFItemID='" + txtProductFItemID.Text + "'")) + 1);
                    if (CvtFunc.ToInt(txtVersionNo.Text) - CvtFunc.ToInt(strVisionNo) > 0)
                    {
                        txtVersionNo.Text = strVisionNo;
                    }
                }
                bUpdateResult = base.UpdateData();
                if (!bUpdateResult) return false ;
                if (blnNeedInitProductRev)
                {
                    
                    string strSQL = "select * from rmProduct Where ProductFItemID='" + txtProductFItemID.Text + "'";
                    DataRow drProduct = mdbcon.GetDataFirstRow(strSQL);
                    if (drProduct != null)
                    {
                        string strFields = new RMProductBOMRevDAL().ParameterFields;

                        int i = 0;
                        string strTmpSQL = "update " + (mTypePara == MtnType.isRev ? "rmProductBOMRev" : "rmProductBOMSales") + " " +
                                            "set Quantity='" + drProduct["Quantity"] + "', " +
                                            "BaseSetSize='" + drProduct["BaseSetSize"] + "'," +
                                            "BaseProductLength='" + drProduct["BaseProductLength"] + "'," +
                                            "BaseProductWidth='" + drProduct["BaseProductWidth"] + "'," +
                                            "BaseMaterialLength='" + drProduct["BaseMaterialLength"] + "'," +
                                            "BaseMaterialWidth='" + drProduct["BaseMaterialWidth"] + "'," +
                                            "BaseMaterialWeight='" + drProduct["BaseMaterialWeight"] + "'," +

                                            "InnerCirclePaperWidth='" + drProduct["InnerCirclePaperWidth"] + "'," +
                                            "InnerWeight='" + drProduct["InnerWeight"] + "'," +
                                            "InnerHeight='" + drProduct["InnerHeight"] + "'," +
                                            "InnerSetSize='" + drProduct["InnerSetSize"] + "'," +
                                            "InnerPages='" + drProduct["InnerPages"] + "'," +
                                            "InnerCutFactor='" + drProduct["InnerCutFactor"] + "'," +
                                            "InnerJoinWidth='" + drProduct["InnerJoinWidth"] + "'," +
                                            "InnerProdLength='" + drProduct["InnerProdLength"] + "'," +
                                            "InnerProdWidth='" + drProduct["InnerProdWidth"] + "'," +
                                            "InnerCutSize='" + drProduct["InnerCutSize"] + "'," +
                                            "InnerJoinLength='" + drProduct["InnerJoinLength"] + "'," +

                                            "FrontCoverHeight='" + drProduct["FrontCoverHeight"] + "'," +
                                            "BackCoverHeight='" + drProduct["BackCoverHeight"] + "'," +
                                            "FrontCoverSize='" + drProduct["FrontCoverSize"] + "'," +
                                            "BackCoverSize='" + drProduct["BackCoverSize"] + "'," +
                                            "BackMateriallFactor='" + drProduct["BackMateriallFactor"] + "'," +
                                            "BackPSFactor='" + drProduct["BackPSFactor"] + "'," +
                                            "PagePrintLength='" + drProduct["PagePrintLength"] + "'," +
                                            "PagePrintWidth='" + drProduct["PagePrintWidth"] + "'," +
                                            "CoverJoinLength='" + drProduct["CoverJoinLength"] + "'," +
                                            "CoverJoinWidth='" + drProduct["CoverJoinWidth"] + "'," +
                                            "CoverMaterialLength='" + drProduct["CoverMaterialLength"] + "'," +
                                            "CoverMaterialWidth='" + drProduct["CoverMaterialWidth"] + "'," +
                                            "BackPSQty1='" + drProduct["BackPSQty1"] + "'," +
                                            "BackPSQty2='" + drProduct["BackPSQty2"] + "'," +
                                            "BackPSQty3='" + drProduct["BackPSQty3"] + "'," +
                                            "BackPSQty4='" + drProduct["BackPSQty4"] + "'," +
                                            "BackCutFactor1='" + drProduct["BackCutFactor1"] + "'," +
                                            "BackCutFactor2='" + drProduct["BackCutFactor2"] + "'," +
                                            "BackPrintInnerQty='" + drProduct["BackPrintInnerQty"] +"',"+
                                            "BackPrintInnerQty2='" + drProduct["BackPrintInnerQty2"] + "'," +
                                            "LaminatingLength='" + drProduct["LaminatingLength"] + "'," +
                                            "LaminatingWidth='" + drProduct["LaminatingWidth"] + "'," +

                                            "HCWeight='" + drProduct["HCWeight"] + "'," +
                                            "HCSetSize='" + drProduct["HCSetSize"] + "'," +
                                            "HCHeight='" + drProduct["HCHeight"] + "'," +
                                            "HCPages='" + drProduct["HCPages"] + "'," +

                                            "StEDPageWeigth='" + drProduct["StEDPageWeigth"] + "'," +
                                            "StEDPageSetSize='" + drProduct["StEDPageSetSize"] + "'," +
                                            "StEDPageHeight='" + drProduct["StEDPageHeight"] + "'," +
                                            "StEDPagePages='" + drProduct["StEDPagePages"] + "'," +
                                            "StEDPageCirclePaperWidth='"+ drProduct["StEDPageCirclePaperWidth"] +"',"+

                                            "PKGContainQty='" + drProduct["PKGContainQty"] + "'," +
                                            "PKGPackageQty='" + drProduct["PKGPackageQty"] + "'," +
                                            "PKGInnerDiameterLength='" + drProduct["PKGInnerDiameterLength"] + "'," +
                                            "PKGInnerDiameterWidth='" + drProduct["PKGInnerDiameterWidth"] + "'," +
                                            "PKGInnerDiameterHeight='" + drProduct["PKGInnerDiameterHeight"] + "'," +
                                            "PKGRows='" + drProduct["PKGRows"] + "'," +
                                            "PKGQty='" + drProduct["PKGQty"] + "'," +

                                            "OthersLockingWireQty='" + drProduct["OthersLockingWireQty"] + "'," +
                                            "OthersLockingWireLength='" + drProduct["OthersLockingWireLength"] + "'," +
                                            "OthersBackWidth='" + drProduct["OthersBackWidth"] + "'," +
                                            "OthersUseIronNailQty='" + drProduct["OthersUseIronNailQty"] + "'," +
                                            "OthersMiddleWidth='" + drProduct["OthersMiddleWidth"] + "'," +
                                            "OthersSheetSize='" + drProduct["OthersSheetSize"] + "'," +
                                            "OthersBurrWidth='" + drProduct["OthersBurrWidth"] + "'," +
                                            "OthersWireLength='" + drProduct["OthersWireLength"] + "'," +
                                            "OthersMiddleSize='" + drProduct["OthersMiddleSize"] + "'," +
                                            "OthersSheetLength='" + drProduct["OthersSheetLength"] + "'," +
                                            "OthersSheetWidth='" + drProduct["OthersSheetWidth"] + "'," +
                                            "OthersOneSheetLength='" + drProduct["OthersOneSheetLength"] + "'," +
                                            "OthersBackQty='" + drProduct["OthersBackQty"] + "'," +
                                            "OthersBackPaperQty='" + drProduct["OthersBackPaperQty"] + "'," +
                                            
                                            "OthersCopyPaperPS1='" + drProduct["OthersCopyPaperPS1"] + "'," +
                                            "OthersCopyPaperPS2='" + drProduct["OthersCopyPaperPS2"] + "'";
                        strTmpSQL += " where ProductFItemID='" + txtProductFItemID.Text + "' and versionNo='" + txtVersionNo.Text + "'";
                        mdbcon.ExecuteSql(strTmpSQL);
                        frmParameter.FillContent(this.RecID.ToString());
                    }
                    strSQL = "Delete from " + (mTypePara == MtnType.isRev ? "rmProductBOMDetailRev" : "rmProductBOMDetailSales") + " where ProductFItemID='" + txtProductFItemID.Text + "' and versionNo='" + txtVersionNo.Text + "'";
                    mdbcon.ExecuteSql(strSQL); 
                    strSQL = "select * from " + (mTypePara == MtnType.isRev ?  "rmProductBOMDetailRev": "rmProductBOMDetailSales") +" where ProductFItemID='" + txtProductFItemID.Text + "' and versionNo='" + txtVersionNo.Text + "'";
                    DataRow drRow = mdbcon.GetDataFirstRow(strSQL);
                    if (drRow == null)
                    {
                        InitBOMHdr(); 
                    }
                }
                this.TimeStamp = (byte[])mdbcon.GetObjectValue("select RecStamp from " + (mTypePara == MtnType.isRev ? "rmProductBOMRev" : "rmProductBOMSales") + " where RecID='" + this.RecID + "'");
            }
            string strErrMsg = "";
            if (this.dgvBOM.CurrentRow != null)
            {
                if (!CheckDtlRow(ref strErrMsg))
                {
                    MsgBoxEx.Show(strErrMsg, SysVar.WarnTitle);
                    return false;
                }
                else
                {
                    if (CvtFunc.ToInt(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                    {
                        Update_Detail(this.dgvBOM.CurrentRow);
                    }
                }
            }
            if (this.dgvLabourCost.CurrentRow != null)
            {
                if (!CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    if (CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value) != "")
                    {
                        MsgBoxEx.Show(strErrMsg, SysVar.WarnTitle);
                        return false;
                    }
                }
                else
                {
                   if (CvtFunc.ToInt( this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) >0)
                   {
                        Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow);
                   }
                }
            }
            if (frmParameter.ConfirmChange() && !blnNeedInitProductRev)
            {
                frmParameter.UpdateContent();
                foreach (DataGridViewRow dgvRow in this.dgvBOM.Rows)
                {
                    if ( CvtFunc.ToString ( dgvRow.Cells [(int)DtlCol.ValueChanged].Value) =="1") Update_Detail(dgvRow);
                }
                foreach (DataGridViewRow dgvRow in this.dgvLabourCost.Rows)
                {
                    if (CvtFunc.ToString(dgvRow.Cells[(int)LabourCostCol.ValueChanged].Value) == "1") Update_Detail_LabourCost(dgvRow);
                }
            }

            if (this.formStatus == FormStatus.Query)
            {
                string strSQL="update " + ( mTypePara == MtnType.isRev ? "rmProductBOMRev" : "rmProductBOMSales") + " set VerClosed='"+ CvtFunc.ToBoolean ( utrVerClosed.Text)  +"' where RecID='"+ this.m_lRecId  +"'";
                mdbcon.ExecuteSql(strSQL);
            }
            this.TimeStamp = (byte[])mdbcon.GetObjectValue("select RecStamp from " + (mTypePara == MtnType.isRev ? "rmProductBOMRev" : "rmProductBOMSales") + " where RecID='" + this.RecID + "'");
            return bUpdateResult;
        }
        public override bool ConfirmChange()
        {
            return (base.ConfirmChange());
        }
        protected override bool FieldCheck(string strFieldValue, string strFieldName, ref string strErrPrompt)
        {

            //strErrPrompt = string.Empty;
            //DBAccess dBAccess = new DBAccess(false, false);
            //DataRow dr = base.GetCurrentMtnDataRow();

            //RM.BusinessRule.RMProductBOMBRL mBRL = new WP.RM.BusinessRule.RMProductBOMBRL();
            //bool bCheckResult = mBRL.FieldCheck(dBAccess, dr, strFieldName, ref strErrPrompt, this.formStatus);
            //dBAccess.CloseCon();
            //return bCheckResult;
            return true;

        }

        public override void InitDeftValue()
        {            
            base.InitDeftValue();
            txtCreator.Text = SysVar.UserName;
            datCreateDate.Value = DateTime.Now.Date.ToShortDateString ();
            txtVersionNo.Text = "1";// CvtFunc.ToString(CvtFunc.ToInt(DataFunctions.GetFieldValue("rmProductBOMRev", "max(VersionNo)", "1=1")) + 1);
        }

        public override void SetControlEditStatus()
        {          
            base.SetControlEditStatus();
            txtVersionNo.Enabled = false;
            
            if (this.formStatus != FormStatus.AddNew)
            {
                txtCategoryName.Enabled = false;
                txtProductName.Enabled = false;
                txtSetName.Enabled = false;
                txtCreator.Enabled = false;
                datCreateDate.Enabled = false;
                ubtProductName.Enabled = false;

               
            }
            else
            {
                txtCategoryName.Enabled = true ;
                txtProductName.Enabled = true ;
                txtSetName.Enabled = true ;
                txtCreator.Enabled = true ;
                datCreateDate.Enabled = true ;
                ubtProductName.Enabled = true;
            }
            utrVerClosed.Enabled = true;
            if (mTypePara == MtnType.isRev)
            {
                lblSalesProductName.Visible = false;
                txtSalesProductName.Visible = false;
            }
            else
            {
                lblSalesProductName.Visible = true;
                txtSalesProductName.Visible = true;
            }
        }
        protected override string GetLookUpSQL(string strTableName, string strLookUpControlName)
        {
            string strSql = string.Empty;
            strSql = base.GetLookUpSQL(strTableName, strLookUpControlName);
            string strMainSQL = BaseFunctions.GetSqlParts ( strSql, SqlOption.SqlPartMain); 
            string strWhere = BaseFunctions.GetSqlParts( strSql , SqlOption.SqlPartWhere );
            string strOrderBy = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartOrderBy); 
            if (strLookUpControlName == this.ubtCategoryName.Name)
            {
                strSql = base.GetLookUpSQL(strTableName, strLookUpControlName);

            }
            else if (strLookUpControlName == this.ubtSetName.Name)
            {

            }
            else if ( strLookUpControlName == this.ubtProductName.Name )
            {
                if (strWhere == "")
                {
                    strWhere = " where 1=1 ";
                }
                if (txtCategoryName.Text !="")
                {
                    strWhere +=" and CategoryName='"+ txtCategoryName.Text +"' " ; 
                }
                if (txtSetName.Text != "")
                {
                    strWhere += " and SetName='" + txtSetName.Text + "'";
                }
                else
                {
                    return strSql;
                }
            }
            return base.GetLookUpSQL(strTableName, strLookUpControlName);
        }

        protected override void ubtLookUp_Click(object sender, EventArgs e)
        {
            Control con = sender as Control;
            if (con.Name == ubtProductName.Name)
            {
                string strSQL = BaseFunctions.GetLookUpSQL("rmProduct");
                frmLookUpProduct frmlookup = new frmLookUpProduct(strSQL, "产成品选择", con.Text, "ProductName");
                frmlookup.ShowDialog();
                if (frmlookup.HaveReturnValue)
                {
                    txtProductName.Text = frmlookup.GetReturnValue("ProductName");
                    txtProductID.Text = frmlookup.GetReturnValue("ProductID");
                    txtProductFItemID.Text = frmlookup.GetReturnValue("ProductFItemID");
                    //txtProductType.Text = frmlookup.GetReturnValue("ProductType");

                    txtCategoryName.Text = DataFunctions.GetFieldValue("rmProduct", "CategoryName", "ProductFItemID='" + txtProductFItemID.Text + "'");
                    txtSetName.Text = DataFunctions.GetFieldValue("rmProduct", "SetName", "ProductFItemID='" + txtProductFItemID.Text + "'");
                    txtCategoryID.Text = DataFunctions.GetFieldValue("rmProduct", "CategoryID", "ProductFItemID='" + txtProductFItemID.Text + "'");
                    txtSetID.Text = DataFunctions.GetFieldValue("rmProduct", "SetID", "ProductFItemID='" + txtProductFItemID.Text + "'");
                }
                frmlookup.Close();
            }
            else
            {
                base.ubtLookUp_Click(sender, e);
            }
        }

        public override void SetButtonStatus()
        {
           
            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnTallyCalculate.Enabled = false;
                    btnCondition.Enabled =  false ;
                    btnCopyToNewVer.Enabled = false ;
                    break;
                case FormStatus.Delete:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = true;
                    this.btnCancel.Enabled = false;
                    this.btnTallyCalculate.Enabled = false;
                    btnCondition.Enabled = true  ;
                    btnCopyToNewVer.Enabled = true  ;
                    break;
                case FormStatus.Query:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = (true && this.CurrentMenuInfo.strPermit == "Y");
                    this.btnNew.Visible = true ;
                    this.btnCancel.Enabled = false;
                    this.btnTallyCalculate.Enabled = false;
                    btnCondition.Enabled = true;
                    btnCopyToNewVer.Enabled = true;
                    btnUpdate.Enabled = true;
                    break;
                case FormStatus.Update:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = true;
                    this.btnNew.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnAddLine.Enabled = true;
                    this.btnTallyCalculate.Enabled = true;
                    btnCondition.Enabled = false ;
                    btnCopyToNewVer.Enabled = false ;
                    this.btnCopyBOMToLabour.Enabled = true;
                    break;
                case FormStatus.Loading:
                    break;

            }

            //this.btnToExcel.Visible = (this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query) && SysVar.AbleToExcel;
            //this.btnToExcel.Enabled = this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query;
            this.btnToExcel.Visible =  SysVar.AbleToExcel;
            this.btnToExcel.Enabled = true ;
            newToolStripMenuItem.Enabled = btnNew.Enabled;
            cancelToolStripMenuItem.Enabled = btnCancel.Enabled;
            deleteToolStripMenuItem.Enabled = btnDelete.Enabled;
            saveToolStripMenuItem.Enabled = btnUpdate.Enabled;
            //btnCondition.Enabled = true;
            //btnCopyToNewVer.Enabled = true;
            this.btnTallyCalculate.Enabled = CvtFunc.ToBoolean(DataFunctions.GetFieldValue(mdbcon, "muser", "AbleToChangeBOMFormula", "username='" + SysVar.UserName + "'"));
            this.btnTop.Enabled = true;
            this.btnBottom.Enabled = true;
            this.btnPrev.Enabled = true;
            this.btnNext.Enabled = true;
            this.btnHelp.Enabled = true;
            this.btnExit.Enabled = true;


            this.btnTop.Visible = false;
            this.btnBottom.Visible = false;
            this.btnPrev.Visible = false;
            this.btnNext.Visible = false;
        }

        public override void SetOtherStatus()
        {
           
            mblnSettingStatus = true;           
            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    this.txtCategoryName.Focus();
                    break;
                case FormStatus.Delete:
                    this.btnNew.Enabled = false;
                    break;
                case FormStatus.Query:
                    break;
                case FormStatus.Update:
                    this.btnNew.Enabled = true;
                    break;
                case FormStatus.Loading:
                    this.btnNew.Enabled = false;
                    break;
            }
            mblnSettingStatus = false;           
        }

        protected override void ShowOtherData()
        {
            base.ShowOtherData();           
            if (this.formStatus != FormStatus.Delete)
            {
                frmParameter.FillContent(m_lRecId.ToString());

                InitGridDtl();
                FillDtl(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtVersionNo.Text );
                ShowLabourCost();
            }
            FillHdrData(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtVersionNo.Text, txtTechnicsName.Text);            
        }

        private void FillHdrData(string strCategoryID, string strSetID, string strProductFItemID, string strVersionNo, string strTechnicsName)
        {
            string strSQL = "select * from rmProductBOMHdr where CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}' ";
            strSQL = string.Format(strSQL, strCategoryID, strSetID, strProductFItemID,strTechnicsName);
            DBAccess dbcon = new DBAccess(false, false);
            DataRow drHdr = dbcon.GetDataFirstRow(strSQL);
            if (drHdr != null)
            {
                //TotalLabourCost,TotalWastageCost,TotalDetailCost,TotalCost
                txtTotalDetailCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalDetailCost"], "Ns.2");
                txtTotalWastageCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalWastageCost"], "Ns.2");
                txtTotalLabourCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalLabourCost"], "Ns.2");
                txtTotalCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalCost"], "Ns.2");
                txtTotalWorkCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalWorkCost"], "Ns.2");
            }

            strSQL = "select * from "+ ( mTypePara == MtnType.isRev ? "rmProductBOMRev": "rmProductBOMSales" ) +" where CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and VersionNo='{3}'";
            strSQL = string.Format(strSQL, strCategoryID, strSetID, strProductFItemID, strVersionNo );
            dbcon = new DBAccess(false, false);
            drHdr = dbcon.GetDataFirstRow(strSQL);
            if (drHdr != null)
            {
                //TotalLabourCost,TotalWastageCost,TotalDetailCost,TotalCost
                txtTotalDetailCostRev.Text = BaseFunctions.FormatNumeric(drHdr["TotalDetailCostRev"], "Ns.2");
                txtTotalWastageCostRev.Text = BaseFunctions.FormatNumeric(drHdr["TotalWastageCostRev"], "Ns.2");
                txtTotalLabourCostRev.Text = BaseFunctions.FormatNumeric(drHdr["TotalLabourCostRev"], "Ns.2");
                txtTotalCostRev.Text = BaseFunctions.FormatNumeric(drHdr["TotalCostRev"], "Ns.2");
                txtTotalWorkCostRev.Text = BaseFunctions.FormatNumeric(drHdr["TotalWorkCostRev"], "Ns.2");

                txtTotalDetailCostDiff.Text = BaseFunctions.FormatNumeric(drHdr["TotalDetailCostDiff"], "Ns.2");
                txtTotalWastageCostDiff.Text = BaseFunctions.FormatNumeric(drHdr["TotalWastageCostDiff"], "Ns.2");
                txtTotalLabourCostDiff.Text = BaseFunctions.FormatNumeric(drHdr["TotalLabourCostDiff"], "Ns.2");
                txtTotalCostDiff.Text = BaseFunctions.FormatNumeric(drHdr["TotalCostDiff"], "Ns.2");
                txtTotalWorkCostDiff.Text = BaseFunctions.FormatNumeric(drHdr["TotalWorkCostDiff"], "Ns.2");

                txtStartCost.Text = BaseFunctions.FormatNumeric(drHdr["StartCost"], "Ns.2");
                txtVersionCost.Text = BaseFunctions.FormatNumeric(drHdr["VersionCost"], "Ns.2");
                txtOtherCost.Text = BaseFunctions.FormatNumeric(drHdr["OtherCost"], "Ns.2");

                double dblQuantity = CvtFunc.ToDouble(DataFunctions.GetFieldValue((mTypePara == MtnType.isRev ? "rmProductBOMRev" : "rmProductBOMSales"), "Quantity", "ProductFItemID='" + txtProductFItemID.Text + "'"));
                txtVerUnitCost.Text = BaseFunctions.FormatNumeric((CvtFunc.ToDouble(txtTotalCostRev.Text) + CvtFunc.ToDouble(txtOtherCost.Text) + CvtFunc.ToDouble(txtVersionCost.Text) + CvtFunc.ToDouble(txtStartCost.Text)) / dblQuantity, "Ns.4");
            }           
        }

        public override void RefreshOverView()
        {
            base.RefreshOverView();
            if (this.RecID != -1)
                this.dgList.RecID = this.RecID;
        }

        private void FillLookUpInfo()
        {
            SetFieldLookUpInfo("CategoryName", "rmCategory", "CategoryName", "ubtCategoryName");
            SetFieldLookUpInfo("CategoryID", "rmCategory", "CategoryID", "ubtCategoryName");
            
            SetFieldLookUpInfo("SetName", "rmSet", "SetName", "ubtSetName");
            SetFieldLookUpInfo("SetID", "rmSet", "SetID", "ubtSetName");

            SetFieldLookUpInfo("ProductName", "rmProductBOMHdr", "ProductName", "ubtProductName");
            SetFieldLookUpInfo("ProductFItemID", "rmProductBOMHdr", "ProductFItemID", "ubtProductName");
            SetFieldLookUpInfo("TechnicsName", "rmProductBOMHdr", "TechnicsName", "ubtProductName");
            SetFieldLookUpInfo("ProductID", "rmProductBOMHdr", "ProductID", "ubtProductName");
        }

        #endregion Form Functions***


        #region Grid
        private void InitGridDtl()
        {
            // RowSeqNo = 0,SeqNo,WKName,WKRemark,CategoryName,SetName
            // IsKeyWK,  ItemNo, ItemName, Price, PriceUnit,
            // Qty, WastageRate, RatedCost,LabourCost, TotalCost,         
            this.dgvBOM.Columns.Clear();
            this.dgvBOM.Rows.Clear();

            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;
            colRowSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colSeqNo = new DataGridViewTextBoxColumn();
            colSeqNo.HeaderText = "序号";
            colSeqNo.Visible = false;
            colSeqNo.Name = "SeqNo";
            colSeqNo.Width = 50;
            colSeqNo.ReadOnly = false;
            colSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colVersionNo = new DataGridViewTextBoxColumn();
            colVersionNo.HeaderText = "版本号";
            colVersionNo.Visible = false;
            colVersionNo.Name = "VersionNo";
            colVersionNo.Width = 50;
            colVersionNo.ReadOnly = false;
            colVersionNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colProductFItemID = new DataGridViewTextBoxColumn();
            colProductFItemID.HeaderText = "成品编码";
            colProductFItemID.Visible = false;
            colProductFItemID.Name = "ProductFItemID";
            colProductFItemID.Width = 50;
            colProductFItemID.ReadOnly = false;
            colProductFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colProductName = new TextLookUpColumn();
            colProductName.HeaderText = "产品名称";
            colProductName.Width = 150;
            colProductName.Name = "ProductName";
            colProductName.ReadOnly = false;
            colProductName.Visible = false;
            colProductName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colTechnicsName = new DataGridViewTextBoxColumn();
            colTechnicsName.HeaderText = "工艺名称";
            colTechnicsName.Visible = false;
            colTechnicsName.Name = "TechnicsName";
            colTechnicsName.Width = 50;
            colTechnicsName.ReadOnly = false;
            colTechnicsName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colWKID = new DataGridViewListColumn();
            colWKID.HeaderText = "工序编号";
            colWKID.Width = 0;
            colWKID.Name = "WKID";
            colWKID.ReadOnly = true;
            colWKID.Visible = false;

            TextLookUpColumn colWKName = new TextLookUpColumn();
            colWKName.HeaderText = "工序名称";
            colWKName.Width = 150;
            colWKName.Name = "WKName";
            colWKName.ReadOnly = false;
            colWKName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colWKRemark = new DataGridViewListColumn();
            colWKRemark.HeaderText = "工序描述";
            colWKRemark.Width = 0;
            colWKRemark.Name = "WKRemark";
            colWKRemark.ReadOnly = true;
            colWKRemark.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colCategoryID = new DataGridViewListColumn();
            colCategoryID.HeaderText = "类别编码";
            colCategoryID.Width = 80;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = false;
            colCategoryID.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colCategoryName = new DataGridViewListColumn();
            colCategoryName.HeaderText = "类别名称";
            colCategoryName.Width = 80;
            colCategoryName.Name = "CategoryName";
            colCategoryName.ReadOnly = false;
            colCategoryName.Visible = false;
            colCategoryName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colSetID = new DataGridViewListColumn();
            colSetID.HeaderText = "系列编码";
            colSetID.Width = 80;
            colSetID.Name = "SetID";
            colSetID.ReadOnly = false;
            colSetID.Visible = false;
            colSetID.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colSetName = new DataGridViewListColumn();
            colSetName.HeaderText = "系列名称";
            colSetName.Width = 80;
            colSetName.Name = "SetName";
            colSetName.ReadOnly = false;
            colSetName.Visible = false;
            colSetName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewCheckBoxColumn colKeyWK = new DataGridViewCheckBoxColumn();
            colKeyWK.HeaderText = "关键工序";
            colKeyWK.Width = 70;
            colKeyWK.Name = "isKeyWK";
            colKeyWK.ReadOnly = true;
            colKeyWK.Visible = false;
            colKeyWK.Resizable = DataGridViewTriState.False;
            colKeyWK.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewCheckBoxColumn colInputWK = new DataGridViewCheckBoxColumn();
            colInputWK.HeaderText = "投料工序";
            colInputWK.Width = 70;
            colInputWK.Name = "isInputWK";
            colInputWK.ReadOnly = true;
            colInputWK.Visible = false;
            colInputWK.Resizable = DataGridViewTriState.False;
            colInputWK.SortMode = DataGridViewColumnSortMode.NotSortable;

            //ItemNo, ItemName, Price, PriceUnit,Qty, WastageRate,
            DataGridViewTextBoxColumn colFItemID = new DataGridViewTextBoxColumn();
            colFItemID.HeaderText = "物料内码";
            colFItemID.Visible = false;
            colFItemID.Width = 120;
            colFItemID.Name = "FItemID";
            colFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colItemNo = new TextLookUpColumn();
            colItemNo.HeaderText = "材料代码";
            colItemNo.Width = 100;
            colItemNo.Name = "ItemNo";
            colItemNo.ReadOnly = false;
            colItemNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colItemName = new DataGridViewTextBoxColumn();
            colItemName.HeaderText = "材料名称";
            colItemName.Visible = true;
            colItemName.Width = 120;
            colItemName.Name = "ItemName";
            colItemName.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colSupNo = new TextLookUpColumn();
            colSupNo.HeaderText = "供应商代码";
            colSupNo.Width = 100;
            colSupNo.Name = "SupNo";
            colSupNo.ReadOnly = false;
            colSupNo.Visible = false;
            colSupNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colSupName = new DataGridViewTextBoxColumn();
            colSupName.HeaderText = "供应商名称";
            colSupName.Visible = true;
            colSupName.Width = 120;
            colSupName.Name = "SupName";
            colSupName.Visible = false;
            colSupName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colPrice = new DataGridViewTextBoxColumn();
            colPrice.HeaderText = "单价";
            colPrice.Visible = true;
            colPrice.Width = 80;
            colPrice.Name = "Price";
            colPrice.SortMode = DataGridViewColumnSortMode.NotSortable;
            colPrice.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colPrice.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colPriceUnit = new DataGridViewTextBoxColumn();
            colPriceUnit.HeaderText = "单位";
            colPriceUnit.Visible = true;
            colPriceUnit.Width = 60;
            colPriceUnit.Name = "PriceUnit";
            colPriceUnit.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colQty = new DataGridViewTextBoxColumn();
            colQty.HeaderText = "定额数量";
            colQty.Width = 70;
            colQty.Visible = true;
            colQty.Name = "Qty";
            colQty.SortMode = DataGridViewColumnSortMode.NotSortable;
            colQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colWastageRate = new DataGridViewTextBoxColumn();
            colWastageRate.HeaderText = "损耗率%";
            colWastageRate.Visible = true;
            colWastageRate.Width = 50;
            colWastageRate.Name = "WastageRate";
            colWastageRate.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWastageRate.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            // QtyWastage,DetailCost,LabourCost, TotalCost,
            DataGridViewTextBoxColumn colQtyWastage = new DataGridViewTextBoxColumn();
            colQtyWastage.HeaderText = "损耗数量";
            colQtyWastage.Visible = false;
            colQtyWastage.Width = 70;
            colQtyWastage.Name = "QtyWastage";
            colQtyWastage.SortMode = DataGridViewColumnSortMode.NotSortable;
            colQtyWastage.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQtyWastage.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colDetailCost = new DataGridViewTextBoxColumn();
            colDetailCost.HeaderText = "定额成本";
            colDetailCost.Visible = true;
            colDetailCost.Width = 70;
            colDetailCost.Name = "DetailCost";
            colDetailCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colDetailCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDetailCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colLabourCost = new DataGridViewTextBoxColumn();
            colLabourCost.HeaderText = "人工成本";
            colLabourCost.Visible = false;
            colLabourCost.Width = 70;
            colLabourCost.Name = "LabourCost";
            colLabourCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colLabourCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colLabourCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colTotalCost = new DataGridViewTextBoxColumn();
            colTotalCost.HeaderText = "总单价";
            colTotalCost.Visible = true;
            colTotalCost.Width = 80;
            colTotalCost.Name = "TotalCost";

            colTotalCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalCost.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            colItemName.ReadOnly = true;
            colSupNo.ReadOnly = true;
            colSupName.ReadOnly = true;

            this.dgvBOM.Columns.AddRange(new DataGridViewColumn[] { colRowSeqNo, colSeqNo, colVersionNo,colProductFItemID ,colProductName,colWKID ,colWKName, colWKRemark, colKeyWK, colInputWK  ,
                                                                    colCategoryID , colCategoryName, colSetID ,colSetName ,
                                                                    colFItemID , colItemNo, colItemName,colSupNo,colSupName , colPrice, colPriceUnit,colQty, colWastageRate,
                                                                    colQtyWastage,colDetailCost,colLabourCost, colTotalCost,colTechnicsName,
                                                                    colRecID, colValueChanged, colDel });

            mDtlColumnReadOnlyArray = new bool[dgvBOM.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgvBOM.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvBOM.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray[i] = dgvBOM.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvBOM.Columns.Count) dgvBOM.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }

            this.dgvBOM.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgvBOM.RowTemplate.Height = 20;
            this.dgvBOM.RowHeadersWidth = 23;
            this.dgvBOM.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgvBOM.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgvBOM.ColumnHeadersHeight = 30;
            this.dgvBOM.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvBOM.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgvBOM.AllowUserToResizeRows = false;

        }
        private void InitGridDtlLabourCost()
        {

            //RowSeqNo =0,
            //SeqNo,WKName,WKRemark,CategoryName , SetName  ,ProductName     ,ItemNo                  
            this.dgvLabourCost.Columns.Clear();
            this.dgvLabourCost.Rows.Clear();

            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;

            DataGridViewTextBoxColumn colHdrSeqNo = new DataGridViewTextBoxColumn();
            colHdrSeqNo.HeaderText = "BOM序号";
            colHdrSeqNo.Visible = false;
            colHdrSeqNo.Name = "BOMSeqNo";
            colHdrSeqNo.Width = 50;
            colHdrSeqNo.ReadOnly = true;

            DataGridViewTextBoxColumn colSeqNo = new DataGridViewTextBoxColumn();
            colSeqNo.HeaderText = "序号";
            colSeqNo.Visible = false;
            colSeqNo.Name = "SeqNo";
            colSeqNo.Width = 50;
            colSeqNo.ReadOnly = false;

            DataGridViewListColumn colWKID = new DataGridViewListColumn();
            colWKID.HeaderText = "工序编号";
            colWKID.Width = 0;
            colWKID.Name = "WKID";
            colWKID.ReadOnly = true;
            colWKID.Visible = false;

            TextLookUpColumn colWKName = new TextLookUpColumn();
            colWKName.HeaderText = "工序名称";
            colWKName.Width = 100;
            colWKName.Name = "WKName";
            colWKName.ReadOnly = false;

            DataGridViewListColumn colWKPriceType = new DataGridViewListColumn();
            colWKPriceType.HeaderText = "工价类别";
            colWKPriceType.Width = 100;
            colWKPriceType.Name = "WKPriceType";
            colWKPriceType.ReadOnly = true;

            DataGridViewListColumn colWKRemark = new DataGridViewListColumn();
            colWKRemark.HeaderText = "工序描述";
            colWKRemark.Width = 0;
            colWKRemark.Name = "WKRemark";
            colWKRemark.ReadOnly = true;

            DataGridViewCheckBoxColumn colKeyWK = new DataGridViewCheckBoxColumn();
            colKeyWK.HeaderText = "关键工序";
            colKeyWK.Width = 60;
            colKeyWK.Name = "isKeyWK";
            colKeyWK.ReadOnly = false ;
            colKeyWK.Visible = true ;
            colKeyWK.Resizable = DataGridViewTriState.False;
            colKeyWK.SortMode = DataGridViewColumnSortMode.NotSortable;


            DataGridViewTextBoxColumn colWKOutName = new DataGridViewTextBoxColumn();
            colWKOutName.HeaderText = "工序产出";
            colWKOutName.Width = 70;
            colWKOutName.Name = "WKOutName";
            colWKOutName.ReadOnly = false;
            colWKOutName.Resizable = DataGridViewTriState.False;
            colWKOutName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colCategoryID = new DataGridViewListColumn();
            colCategoryID.HeaderText = "类别编码";
            colCategoryID.Width = 60;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = false;

            DataGridViewListColumn colCategoryName = new DataGridViewListColumn();
            colCategoryName.HeaderText = "类别名称";
            colCategoryName.Width = 60;
            colCategoryName.Name = "CategoryName";
            colCategoryName.ReadOnly = false;
            colCategoryName.Visible = false;

            DataGridViewListColumn colSetID = new DataGridViewListColumn();
            colSetID.HeaderText = "系列编码";
            colSetID.Width = 80;
            colSetID.Name = "SetID";
            colSetID.ReadOnly = false;
            colSetID.Visible = false;

            DataGridViewListColumn colSetName = new DataGridViewListColumn();
            colSetName.HeaderText = "系列名称";
            colSetName.Width = 80;
            colSetName.Name = "SetName";
            colSetName.ReadOnly = false;
            colSetName.Visible = false;

            DataGridViewTextBoxColumn colVersionNo = new DataGridViewTextBoxColumn();
            colVersionNo.HeaderText = "版本号";
            colVersionNo.Visible = false;
            colVersionNo.Name = "VersionNo";
            colVersionNo.Width = 50;
            colVersionNo.ReadOnly = false;
            colVersionNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colProductFItemID = new DataGridViewListColumn();
            colProductFItemID.HeaderText = "产成品编码";
            colProductFItemID.Width = 80;
            colProductFItemID.Name = "ProductFItemID";
            colProductFItemID.ReadOnly = false;
            colProductFItemID.Visible = false;


            DataGridViewListColumn colProductName = new DataGridViewListColumn();
            colProductName.HeaderText = "产成品名称";
            colProductName.Width = 80;
            colProductName.Name = "ProductName";
            colProductName.ReadOnly = false;
            colProductName.Visible = false;

            DataGridViewTextBoxColumn colFItemID = new DataGridViewTextBoxColumn();
            colFItemID.HeaderText = "物料内码";
            colFItemID.Visible = false;
            colFItemID.Width = 120;
            colFItemID.Name = "FItemID";
            colFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colItemNo = new TextLookUpColumn();
            colItemNo.HeaderText = "物料代码";
            colItemNo.Width = 80;
            colItemNo.Name = "ItemNo";
            colItemNo.ReadOnly = false;
            colItemNo.Visible = false ;

            DataGridViewTextBoxColumn colItemName = new DataGridViewTextBoxColumn();
            colItemName.HeaderText = "物料名称";
            colItemName.Visible = false;
            colItemName.Name = "ItemName";
            colItemName.Width = 50;
            colItemName.ReadOnly = true;

            //CalUnit,CutType,WorkQty, TotalQty,    //总数量            
            TextLookUpColumn colCalUnit = new TextLookUpColumn();
            colCalUnit.HeaderText = "计件单位";
            colCalUnit.Width = 100;
            colCalUnit.Name = "CalUnit";
            colCalUnit.ReadOnly = false;

            TextLookUpColumn colCutType = new TextLookUpColumn();
            colCutType.HeaderText = "分切系数";
            colCutType.Visible = true;
            colCutType.Width =50;
            colCutType.Name = "CutType";

            DataGridViewTextBoxColumn colWorkQty = new DataGridViewTextBoxColumn();
            colWorkQty.HeaderText = "总数量";
            colWorkQty.Width = 70;
            colWorkQty.Visible = true;
            colWorkQty.Name = "WorkQty";
            colWorkQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWorkQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colTotalQty = new DataGridViewTextBoxColumn();
            colTotalQty.HeaderText = "计量数量";
            colTotalQty.Width = 60;
            colTotalQty.Visible = true;
            colTotalQty.Name = "TotalQty";
            colTotalQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            //StandardQty, //10小时额定产量
            //spendHours,   //预计用工时间
            //StandardWage,  // 固定工资          
            DataGridViewTextBoxColumn colStandardQty = new DataGridViewTextBoxColumn();
            colStandardQty.HeaderText = "额定产量(10小时)";
            colStandardQty.Visible = true;
            colStandardQty.Width = 50;
            colStandardQty.Name = "StandardQty";

            DataGridViewTextBoxColumn colSpendHours = new DataGridViewTextBoxColumn();
            colSpendHours.HeaderText = "耗用工时";
            colSpendHours.Visible = true;
            colSpendHours.Width = 45;
            colSpendHours.Name = "SpendHours";
            colSpendHours.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colSpendHours.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colStandardWage = new DataGridViewTextBoxColumn();
            colStandardWage.HeaderText = "固定工资";
            colStandardWage.Visible = true;
            colStandardWage.Width = 70;
            colStandardWage.Name = "StandardWage";
            colStandardWage.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colStandardWage.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            //StandardWage26, //26天标准工资
            //UnitCost,        //记件工价
            //Remark,         //备注 
            DataGridViewTextBoxColumn colStandardWage26 = new DataGridViewTextBoxColumn();
            colStandardWage26.HeaderText = "标准工资(26天)";
            colStandardWage26.Visible = true;
            colStandardWage26.Width = 60;
            colStandardWage26.Name = "StandardWage26";
            colStandardWage26.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colStandardWage26.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colUnitCost = new DataGridViewTextBoxColumn();
            colUnitCost.HeaderText = "计件工价";
            colUnitCost.Visible = true;
            colUnitCost.Width = 65;
            colUnitCost.Name = "UnitCost";
            colUnitCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colUnitCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            
            DataGridViewTextBoxColumn colTotUnitCost = new DataGridViewTextBoxColumn();
            colTotUnitCost.HeaderText = "计件工资";
            colTotUnitCost.Visible = true;
            colTotUnitCost.Width = 70;
            colTotUnitCost.Name = "TotUnitCost";
            colTotUnitCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotUnitCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colDtlLaborTotCost = new DataGridViewTextBoxColumn();
            colDtlLaborTotCost.HeaderText = "人工成本";
            colDtlLaborTotCost.Visible = true;
            colDtlLaborTotCost.Width = 70;
            colDtlLaborTotCost.Name = "";
            colDtlLaborTotCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDtlLaborTotCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colWorkCost = new DataGridViewTextBoxColumn();
            colWorkCost.HeaderText = "工时费用标准";
            colWorkCost.Visible = true;
            colWorkCost.Width = 60;
            colWorkCost.Name = "WorkCost";
            colWorkCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWorkCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colDetailTotWorkCost = new DataGridViewTextBoxColumn();
            colDetailTotWorkCost.HeaderText = "工时费用";
            colDetailTotWorkCost.Visible = true;
            colDetailTotWorkCost.Width = 60;
            colDetailTotWorkCost.Name = "DetailTotWorkCost";
            colDetailTotWorkCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDetailTotWorkCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;


            DataGridViewTextBoxColumn colRemark = new DataGridViewTextBoxColumn();
            colRemark.HeaderText = "备注";
            colRemark.Visible = true;
            colRemark.Width = 80;
            colRemark.Name = "Remark";
            colRemark.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colRemark.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colTechnicsName = new DataGridViewTextBoxColumn();
            colTechnicsName.HeaderText = "工艺名称";
            colTechnicsName.Visible = false;
            colTechnicsName.Name = "TechnicsName";
            colTechnicsName.Width = 50;
            colTechnicsName.ReadOnly = false;
            colTechnicsName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            //RowSeqNo =0,
            //SeqNo,WKName,WKRemark,CategoryName , SetName   
            //CalUnit,CutType, TotalQty,    //总数量 
            //StandardQty, //10小时额定产量
            //spendHours,   //预计用工时间
            //StandardWage,  // 固定工资   
            //StandardWage26, //26天标准工资
            //UnitCost,        //记件工价
            //Remark,         //备注 
            this.dgvLabourCost.Columns.AddRange(new DataGridViewColumn[] { colRowSeqNo,colHdrSeqNo, colSeqNo,colWKID , colWKName, colWKPriceType, colWKRemark, colKeyWK , colWKOutName , colCategoryID , colCategoryName, colSetID ,colSetName , colVersionNo , 
                                                                    colProductFItemID , colProductName, colFItemID  ,colItemNo,colItemName  ,
                                                                    colCalUnit , colCutType  , colWorkQty  ,colTotalQty , colStandardQty  ,colSpendHours, colStandardWage  ,
                                                                    colStandardWage26, colUnitCost,colTotUnitCost,colDtlLaborTotCost,colWorkCost,colDetailTotWorkCost , colRemark , colTechnicsName ,
                                                                    colRecID, colValueChanged, colDel  });

            mDtlColumnReadOnlyArray_LabourCost = new bool[dgvLabourCost.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgvLabourCost.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvLabourCost.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray_LabourCost[i] = dgvLabourCost.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvLabourCost.Columns.Count) dgvLabourCost.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }

            this.dgvLabourCost.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgvLabourCost.RowTemplate.Height = 20;
            this.dgvLabourCost.RowHeadersWidth = 23;
            this.dgvLabourCost.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgvLabourCost.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgvLabourCost.ColumnHeadersHeight = 40;
            this.dgvLabourCost.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvLabourCost.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgvLabourCost.AllowUserToResizeRows = false;

        }

        private void AddDtlRow(string strGridName)
        {
            AddDtlRow(strGridName, -1);
        }

        private void RefershRowSeqNo(string strGridName)
        {          
            DBAccess dbCon = new DBAccess(false, false);
            if (this.tbcMain.SelectedTab == tbpBOM)
            {
                foreach (DataGridViewRow dgvRow in this.dgvBOM.Rows)
                {
                    string strErrMsg = "";
                    dgvRow.Cells[(int)DtlCol.RowSeqNo].Value = dgvRow.Index + 1;
                    if (this.dgvBOM.CurrentRow.Index < dgvRow.Index)
                    {
                        if (CvtFunc.ToDouble(dgvRow.Cells[(int)DtlCol.RecID].Value) > 0)
                        {
                            string strSQL = "update "+ ( mTypePara == MtnType.isRev ? "rmProductBOMDetailRev" :"rmProductBOMDetailSales") +" set RowSeqNo='" + (dgvRow.Index + 1) + "' where RecID='" + dgvRow.Cells[(int)DtlCol.RecID].Value + "'";
                            dbCon.ExecuteSql(strSQL);
                        }
                    }
                }
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                foreach (DataGridViewRow dgvRow in this.dgvLabourCost.Rows)
                {
                    string strErrMsg = "";
                    dgvRow.Cells[(int)DtlCol.RowSeqNo].Value = dgvRow.Index + 1;
                    if (this.dgvLabourCost.CurrentRow.Index < dgvRow.Index)
                    {
                        if (CvtFunc.ToDouble(dgvRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                        {
                            string strSQL = "update "+ ( mTypePara == MtnType.isRev ? "rmProductBOMLabourCostRev":"rmProductBOMLabourCostSales") +" set RowSeqNo='" + (dgvRow.Index + 1) + "' where RecID='" + dgvRow.Cells[(int)LabourCostCol.RecID].Value + "'";
                            dbCon.ExecuteSql(strSQL);
                        }
                    }
                }
            }
            dbCon.CloseCon(); 
        }

        private void AddDtlRow(string strGridName, double iRow)
        {
            if (strGridName == dgvBOM.Name)
            {
                int intRow = CvtFunc.ToInt(iRow);
                m_bCanTrigerCellValueChangedEven = false;
                if (iRow >= 0)
                {
                    intRow++;
                    this.dgvBOM.Rows.Insert(intRow, 1);
                }
                else
                {
                    this.dgvBOM.Rows.Add();
                    intRow = this.dgvBOM.Rows.Count - 1;
                }
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.RowSeqNo].Value = dgvBOM.Rows.Count.ToString();
                if (mTypePara == MtnType.isRev)
                {
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.SeqNo].Value = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue("rmProductBOMDetailRev", "max(SeqNo)", "ProductName='" + txtProductName.Text + "' and versionNo='" + txtVersionNo.Text + "' and CategoryName='" + txtCategoryName.Text + "' and SetName='" + txtSetName.Name + "'")) + 1);
                }
                else
                {
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.SeqNo].Value = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue("rmProductBOMDetailSales", "max(SeqNo)", "ProductName='" + txtProductName.Text + "' and versionNo='" + txtVersionNo.Text + "' and CategoryName='" + txtCategoryName.Text + "' and SetName='" + txtSetName.Name + "'")) + 1);
                }
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.VersionNo].Value = txtVersionNo.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ProductName].Value = txtProductName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.CategoryName].Value = txtCategoryName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.SetName].Value = txtSetName.Text;

                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ProductFItemID].Value = txtProductFItemID.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.CategoryID].Value = txtCategoryID.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.SetID].Value = txtSetID.Text;

                dgvBOM.Rows[intRow].Cells[(int)DtlCol.IsKeyWK].Value = "false";
                if (dgvBOM.Rows.Count > 0 && intRow >= 1)
                {
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKID].Value = dgvBOM.Rows[intRow - 1].Cells[(int)DtlCol.WKID].Value;
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = dgvBOM.Rows[intRow - 1].Cells[(int)DtlCol.WKRemark].Value;
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName].Value = dgvBOM.Rows[intRow - 1].Cells[(int)DtlCol.WKName].Value;
                }
                else
                {
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKID].Value = "";
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = "";
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName].Value = "";
                }
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ItemNo].Value = "";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ItemName].Value = "";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.LabourCost].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.Price].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.PriceUnit].Value = "";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.Qty].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.QtyWastage].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.DetailCost].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.TotalCost].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.WastageRate].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.RecID].Value = -1;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ValueChanged].Value = "0";
                dgvBOM.CurrentCell = dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName];
                m_bCanTrigerCellValueChangedEven = true;
            }
            else if (strGridName == this.dgvLabourCost.Name)
            {
                int intRow = CvtFunc.ToInt(iRow);
                if (dgvBOM.Rows.Count == 0) return;
                m_bCanTrigerCellValueChangedEven_LabourCost = false;
                if (iRow >= 0)
                {
                    intRow++;
                    this.dgvLabourCost.Rows.Insert(intRow, 1);
                }
                else
                {
                    this.dgvLabourCost.Rows.Add();
                    intRow = this.dgvLabourCost.Rows.Count - 1;
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.RowSeqNo].Value = dgvLabourCost.Rows.Count.ToString();

                string strItemNo = ""; 
                string strBOMSeqNo = "";
                if (dgvBOM.CurrentRow != null)
                {
                   strBOMSeqNo = CvtFunc.ToString(dgvBOM.CurrentRow.Cells[(int)DtlCol.SeqNo].Value);
                   strItemNo = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value);
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.BOMSeqNo].Value = strBOMSeqNo ;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ItemNo].Value = "";//strItemNo ;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ItemName].Value = "";// DataFunctions.GetFieldValue("iminvmaster", "itemname", "itemno='" + strItemNo + "'");
                if (mTypePara == MtnType.isRev)
                {
                    dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SeqNo].Value = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue("rmProductBOMLabourCostRev", "max(SeqNo)", "ProductName='" + txtProductName.Text + "' and VersionNo='" + txtVersionNo.Text + "' and CategoryName='" + txtCategoryName.Text + "' and SetName='" + txtSetName.Name + "'")) + 1);
                }
                else
                {
                    dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SeqNo].Value = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue("rmProductBOMLabourCostSales", "max(SeqNo)", "ProductName='" + txtProductName.Text + "' and VersionNo='"+ txtVersionNo.Text  +"' and CategoryName='" + txtCategoryName.Text + "' and SetName='" + txtSetName.Name + "'")) + 1);
                }

                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CategoryName].Value = txtCategoryName.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SetName].Value = txtSetName.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ProductName].Value = txtProductName.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.VersionNo].Value = txtVersionNo.Text;

                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CategoryID].Value = txtCategoryID.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SetID].Value = txtSetID.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ProductFItemID].Value = txtProductFItemID.Text;

                //if (dgvLabourCost.Rows.Count > 0 && intRow >=1)
                //{

                //    dgvLabourCost.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = dgvLabourCost.Rows[intRow-1].Cells[(int)DtlCol.WKRemark].Value;
                //    dgvLabourCost.Rows[intRow].Cells[(int)DtlCol.WKName].Value = dgvLabourCost.Rows[intRow-1].Cells[(int)DtlCol.WKName].Value;
                //}
                //else
                {
                    dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKRemark].Value = "";
                    dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKName].Value = "";
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CalUnit].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CutType].Value = "1";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardQty].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardWage].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardWage26].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.TotalQty].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.UnitCost].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.UsedHours].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.TotalQty].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.Remark].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.RecID].Value = -1;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ValueChanged].Value = "0";
                this.dgvLabourCost.Columns[(int)LabourCostCol.WKName].ReadOnly = false;
                dgvLabourCost.CurrentCell = dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKName];
                m_bCanTrigerCellValueChangedEven_LabourCost = true;
            }
            RefershRowSeqNo(strGridName);
        }

        private bool CheckDtlRow(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvBOM.ColumnCount - 1; i++)
            {
                bCheckResult = CheckDtlCell(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            return bCheckResult;
        }
        private bool CheckDtlRow_LabourCost(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvLabourCost.ColumnCount - 1; i++)
            {
                bCheckResult = CheckDtlCell_LabourCost(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            return bCheckResult;
        }
        private bool CheckDtlCell(int iColumn, ref string strErrMsg)
        {
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "";
            if (this.dgvBOM.CurrentRow != null && this.dgvBOM.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = this.dgvBOM.CurrentRow.Cells[iColumn].Value.ToString().TrimEnd();
            }
            switch ((DtlCol)iColumn)
            {
                case DtlCol.WKName:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序名称不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureName"))
                    {
                        strErrMsg = "不存在的工序名称";
                        return false;
                    }
                    return true;
                case DtlCol.ItemNo:
                    if (strValue.Trim() == "" && CvtFunc.ToBoolean(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.IsInputWK].Value))
                    {
                        strErrMsg = "投料工序的物料名称不能为空";
                        return false;
                    }
                    else if (!DataFunctions.CheckRecordExist("iminvmaster", strValue, "ItemNo") && strValue != "")
                    {
                        strErrMsg = "不存在的物料编码";
                        return false;
                    }
                    return true;
            }
            return bReturnValue;
        }
        private bool CheckDtlCell_LabourCost(int iColumn, ref string strErrMsg)
        {
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "";
            if (this.dgvLabourCost.CurrentRow != null && this.dgvLabourCost.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = this.dgvLabourCost.CurrentRow.Cells[iColumn].Value.ToString().TrimEnd();
            }
            switch ((LabourCostCol)iColumn)
            {
                case LabourCostCol.WKName:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序名称不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureName"))
                    {
                        strErrMsg = "不存在的工序名称";
                        return false;
                    }
                    return true;
                case LabourCostCol.ItemNo:
                    //if (strValue.Trim() == "" && CvtFunc.ToBoolean(this.dgvLabourCost.CurrentRow.Cells[(int)DtlCol.IsInputWK].Value))
                    //{
                    //    strErrMsg = "投料工序的物料名称不能为空";
                    //    return false;
                    //}
                    //else
                    if (!DataFunctions.CheckRecordExist("iminvmaster", strValue, "ItemNo") && strValue != "")
                    {
                        strErrMsg = "不存在的物料编码";
                        return false;
                    }
                    return true;
            }
            return bReturnValue;
        }

        private void btnAddLine_Click(object sender, EventArgs e)
        {
            string strErrMsg = string.Empty;
            if (this.tbcMain.SelectedTab == tbpBOM)
            {
                if (this.dgvBOM.Rows.Count == 0)
                {
                    AddDtlRow(this.dgvBOM.Name);
                }
                if (CheckDtlRow(ref strErrMsg))
                {
                    if (Update_Detail(this.dgvBOM.CurrentRow))
                    {
                        AddDtlRow(this.dgvBOM.Name, dgvBOM.CurrentCell.RowIndex);
                        RefershRowSeqNo(this.dgvBOM.Name);
                    }
                }
                else if (string.IsNullOrEmpty(strErrMsg))
                {
                    MessageBox.Show(strErrMsg, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                if (this.dgvLabourCost.Rows.Count == 0)
                {
                    AddDtlRow(this.dgvLabourCost.Name);
                }
                else if (CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    if (Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow))
                    {
                        AddDtlRow(this.dgvLabourCost.Name, dgvLabourCost.CurrentCell.RowIndex);
                    }
                }
                else if (!string.IsNullOrEmpty(strErrMsg))
                {
                    MessageBox.Show(strErrMsg, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private bool Update_Detail(DataGridViewRow dgvRow)
        {
            if (this.formStatus == FormStatus.Query) return true;
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            DBAccess dbcon = new DBAccess(false, false);
            try
            {
                dbcon.BeginTran();                
                
                DataRow drBOM = dbcon.GetDataSet("select * from "+ (mTypePara == MtnType.isRev ? "rmProductBOMDetailRev":"rmProductBOMDetailSales") +"").Tables[0].NewRow();
                dgvRow.Cells[(int)DtlCol.RowSeqNo].Value = dgvRow.Index + 1;
                BaseFunctions.FillDataRowByGridRow(dgvRow, drBOM);
                drBOM["CategoryID"] = txtCategoryID.Text;
                drBOM["SetID"] = txtSetID.Text;
                drBOM["ProductFItemID"] = CvtFunc.ToInt ( txtProductFItemID.Text);
                drBOM["TechnicsName"] = txtTechnicsName.Text;
                if (mTypePara == MtnType.isRev)
                {
                    RMProductBOMRevDAL rmRevDAL = new RMProductBOMRevDAL();
                    if (rmRevDAL.UpdateBOMDetail(dbcon, drBOM))
                    {
                        dbcon.CommitTran();
                    }
                    else
                    {
                        dbcon.RollbackTran();
                    }
                }
                else if (mTypePara == MtnType.isSales)
                {
                    RMProductBOMSalesDAL rmSalesDAL = new RMProductBOMSalesDAL();
                    if (rmSalesDAL.UpdateBOMDetail(dbcon, drBOM))
                    {
                        dbcon.CommitTran();
                    }
                    else
                    {
                        dbcon.RollbackTran();
                    }
                }

                dgvRow.Cells[(int)DtlCol.RecID].Value = CvtFunc.ToString(drBOM["RecID"]);
                dgvRow.Cells[(int)DtlCol.Qty].Value =  CvtFunc.ToDouble (drBOM["Qty"]).ToString ("F8");
                dgvRow.Cells[(int)DtlCol.DetailCost].Value = BaseFunctions.FormatNumeric(drBOM["DetailCost"], "Ns.4");
                dgvRow.Cells[(int)DtlCol.TotalCost].Value = BaseFunctions.FormatNumeric(drBOM["TotalCost"], "Ns.4");
                dgvRow.Cells[(int)DtlCol.ValueChanged].Value = "0";
                dgvBOM.EndEdit();
                FillHdrData(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtVersionNo.Text,txtTechnicsName.Text  );
                this.TimeStamp = (byte[])dbcon.GetObjectValue("Select RecStamp From " + this.TableName + " Where Recid=" + m_lRecId);
            }
            catch (Exception ex)
            {
                MsgBoxEx.Show(ex.ToString());
                dbcon.RollbackTran();
                return false;
            }
            dbcon.CloseCon();
            return true;
        }
        private bool Update_Detail_LabourCost(DataGridViewRow dgvRow)
        {
            if (this.formStatus == FormStatus.Query) return true;
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            DBAccess dbcon = new DBAccess(false, false);
            try
            {

                dbcon.BeginTran();                
                DataRow drLabourCost = dbcon.GetDataSet("select top 0 * from "+ (mTypePara == MtnType.isRev ? "rmProductBOMLabourCostRev":"rmProductBOMLabourCostSales")+ "").Tables[0].NewRow();
                dgvRow.Cells[(int)LabourCostCol.RowSeqNo].Value = dgvRow.Index + 1;
                BaseFunctions.FillDataRowByGridRow(dgvRow, drLabourCost);
                drLabourCost["CategoryID"] = txtCategoryID.Text;
                drLabourCost["SetID"] = txtSetID.Text;
                drLabourCost["ProductFItemID"] =CvtFunc.ToInt ( txtProductFItemID.Text);
                if (mTypePara == MtnType.isRev)
                {
                    drLabourCost["TechnicsName"] = txtTechnicsName.Text;
                    RMProductBOMRevDAL rmDAL = new RMProductBOMRevDAL();
                    if (rmDAL.UpdateLabourCostDetail(dbcon, drLabourCost))
                    {
                        dbcon.CommitTran();
                    }
                    else
                    {
                        dbcon.RollbackTran();
                    }
                }
                else
                {
                    drLabourCost["TechnicsName"] = txtTechnicsName.Text;
                    RMProductBOMSalesDAL rmDAL = new RMProductBOMSalesDAL();
                    if (rmDAL.UpdateLabourCostDetail(dbcon, drLabourCost))
                    {
                        dbcon.CommitTran();
                    }
                    else
                    {
                        dbcon.RollbackTran();
                    }
                }

                dgvRow.Cells[(int)LabourCostCol.RecID].Value = CvtFunc.ToString(drLabourCost["RecID"]);
                dgvRow.Cells[(int)LabourCostCol.TotalQty].Value = BaseFunctions.FormatNumeric(drLabourCost["TotalQty"], "Ns.2");
                dgvRow.Cells[(int)LabourCostCol.UnitCost].Value = BaseFunctions.FormatNumeric(drLabourCost["UnitCost"], "Ns.6");
                dgvRow.Cells[(int)LabourCostCol.TotUnitCost].Value = BaseFunctions.FormatNumeric(drLabourCost["TotUnitCost"], "Ns.4");
                dgvRow.Cells[(int)LabourCostCol.UsedHours].Value = BaseFunctions.FormatNumeric(drLabourCost["SpendHours"], "Ns.6");
                dgvRow.Cells[(int)LabourCostCol.TotWorkCost].Value = BaseFunctions.FormatNumeric(drLabourCost["DetailTotWorkCost"], "Ns.2");
                dgvRow.Cells[(int)LabourCostCol.DtlLaborTotCost].Value = BaseFunctions.FormatNumeric(drLabourCost["DetailCost"], "Ns.4");
                dgvRow.Cells[(int)LabourCostCol.ValueChanged].Value = "0";
                dgvLabourCost.EndEdit();
                FillHdrData(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtVersionNo.Text,txtTechnicsName .Text  );
                this.TimeStamp = (byte[])dbcon.GetObjectValue("Select RecStamp From " + this.TableName + " Where Recid=" + m_lRecId);
            }
            catch (Exception ex)
            {
                dbcon.RollbackTran();
                return false;
            }
            dbcon.CloseCon();
            return true;
        }
        private bool Delete_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;            
            DBAccess dbcon = new DBAccess(false, false);
            string strRecID = CvtFunc.ToString(dgvRow.Cells[(int)DtlCol.RecID].Value);
            if (mTypePara == MtnType.isRev)
            {
                RMProductBOMRevBRL rmBRL = new RMProductBOMRevBRL();
                if (rmBRL.DeleteDetailValid(dbcon, strRecID))
                {
                    RMProductBOMRevDAL rmDAL = new RMProductBOMRevDAL();
                    rmDAL.DeleteDetailBOM(dbcon, strRecID);
                }
            }
            else
            {
                RMProductBOMSalesBRL rmBRL = new RMProductBOMSalesBRL();
                if (rmBRL.DeleteDetailValid(dbcon, strRecID))
                {
                    RMProductBOMSalesDAL rmDAL = new RMProductBOMSalesDAL();
                    rmDAL.DeleteDetailBOM(dbcon, strRecID);
                }
            }
            return true;
        }

        private bool Delete_Detail_LabourCost(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            
            DBAccess dbcon = new DBAccess(false, false);
            string strRecID = CvtFunc.ToString(dgvRow.Cells[(int)LabourCostCol.RecID].Value);
            if ( CvtFunc.ToDouble( strRecID ) >0 )
            {
                if (MessageBox.Show("确定要删除此行？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (mTypePara == MtnType.isRev)
                    {
                        RMProductBOMRevDAL rmDAL = new RMProductBOMRevDAL();
                        rmDAL.DeleteDetail_LabourCost(dbcon, strRecID);
                    }
                    else
                    {
                        RMProductBOMSalesDAL rmDAL = new RMProductBOMSalesDAL();
                        rmDAL.DeleteDetail_LabourCost(dbcon, strRecID);
                    }
                }
                else
                    return false;
            }
            return true;
        }

        private void FillDtl(string strCategoryID, string strSetID, string strProductFItemID, string strVersionNo)
        {
            //if ( this.formStatus == FormStatus.AddNew ) InitBOMHdr();
            string strSql = "";
            string strUserName = "";
            string strRecid = "";
            bool bAccess = false;
            m_bCanTrigerCellValueChangedEven = false;

            this.dgvBOM.Rows.Clear();
            DBAccess dbCon = new DBAccess(false, false);

            string strProductName = DataFunctions.GetFieldValue(dbCon, "rmProduct", "ProductName", "ProductFItemID='" + strProductFItemID + "'");
            string strCategoryName = DataFunctions.GetFieldValue(dbCon, "rmCategory", "CategoryName", "CategoryID='" + strCategoryID + "'");
            string strSetName =DataFunctions.GetFieldValue(dbCon,"rmSet" ,"SetName" , "SetID='"+ strSetID +"'" );
            strSql = "select A.* from "+ ( mTypePara == MtnType.isRev ?  "rmProductBOMDetailRev":"rmProductBOMDetailSales") +" A  where A.CategoryID='{0}' and A.SetID='{1}' and A.ProductFItemID='{2}' and A.VersionNo='{3}' order by A.RowSeqNo,A.SeqNo";
            strSql = string.Format(strSql, strCategoryID, strSetID, strProductFItemID, strVersionNo);
            DataTable mUserAlertTable = dbCon.GetDataSet(strSql).Tables[0];
            for (int i = 0; i < mUserAlertTable.Rows.Count; i++)
            {
                DataRow dr = mUserAlertTable.Rows[i];
                if (this.dgvBOM.Rows.Count <= i) this.dgvBOM.Rows.Add();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.RowSeqNo].Value = dgvBOM.Rows.Count.ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SeqNo].Value = dr["SeqNo"].ToString().TrimEnd();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKID].Value = dr["WKID"].ToString().TrimEnd();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKName].Value = DataFunctions.GetFieldValue ( dbCon,"rmWorkingProcedure","WorkingProcedureName","WorkingProcedureID='"+ dr["WKID"] +"'");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.VersionNo].Value = dr["VersionNo"].ToString().TrimEnd();

                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ProductFItemID].Value = dr["ProductFItemID"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SetID].Value = dr["SetID"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.CategoryID].Value = dr["CategoryID"].ToString();

                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ProductName].Value =  strProductName  ;
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.TechnicsName].Value = dr["TechnicsName"].ToString().TrimEnd();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.CategoryName].Value = strCategoryName;
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SetName].Value = strSetName;
                
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.FItemID].Value = CvtFunc.ToString(dr["FItemID"]);
                strSql = "select ItemNo,ItemName from iminvmaster where FItemID='" + CvtFunc.ToString(dr["FItemID"]) + "'";
                DataRow drItemNo = mdbcon.GetDataFirstRow(strSql);
                if (drItemNo == null)
                {

                }
                else
                {
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ItemNo].Value = CvtFunc.ToString(drItemNo["ItemNo"]);
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ItemName].Value = CvtFunc.ToString(drItemNo["ItemName"]);
                }

                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.LabourCost].Value = BaseFunctions.FormatNumeric(dr["LabourCost"], "Ns.4");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.Price].Value = BaseFunctions.FormatNumeric(dr["Price"], "Ns.3");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.PriceUnit].Value = CvtFunc.ToString(dr["PriceUnit"]);
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.Qty].Value = CvtFunc.ToDouble(dr["Qty"]).ToString ("F8");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.QtyWastage].Value = BaseFunctions.FormatNumeric(dr["QtyWastage"], "Ns.2");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WastageRate].Value = BaseFunctions.FormatNumeric(dr["WastageRate"], "Ns.2");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.TotalCost].Value = BaseFunctions.FormatNumeric(dr["TotalCost"], "Ns.4");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.DetailCost].Value = BaseFunctions.FormatNumeric(dr["DetailCost"], "Ns.4");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.IsKeyWK].Value = dr["IsKeyWK"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.IsInputWK].Value = dr["IsInputWK"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SupNo ].Value = dr["SupNo"].ToString ();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SupName].Value = dr["SupName"].ToString () ;
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.RecID].Value = CvtFunc.ToInt(dr["RecID"]);
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ValueChanged].Value = "0";
                
            }//
            this.dgvBOM.EndEdit();
            dbCon.CloseCon();
            base.SetBlankImage(dgvBOM);
            RefershRowSeqNo(this.dgvBOM.Name);
            m_bCanTrigerCellValueChangedEven = true;
        }

        private void FillDtl_LabourCost(string strCategoryID, string strSetID, string strProductFItemID, string strVersionNo)
        {
            string strSql = "";
            string strUserName = "";
            string strRecid = "";
            bool bAccess = false;
            m_bCanTrigerCellValueChangedEven_LabourCost = false;

            this.dgvLabourCost.Rows.Clear();
            DBAccess dbCon = new DBAccess(false, false);

            strSql = "select A.* from " + (mTypePara == MtnType.isRev ? "rmProductBOMLabourCostRev" : "rmProductBOMLabourCostSales") + " A  where A.CategoryID='" + strCategoryID + "' and A.setID='" + strSetID + "' and A.ProductFItemID='" + strProductFItemID + "' and A.VersionNo='" + strVersionNo + "' order by A.RowSeqNo,A.seqno";
            DataTable mUserAlertTable = dbCon.GetDataSet(strSql).Tables[0];
            foreach (DataRow dr in mUserAlertTable.Rows)
            {
                this.dgvLabourCost.Rows.Add();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.RowSeqNo].Value = dgvLabourCost.Rows.Count.ToString();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.BOMSeqNo].Value = dr["BOMSeqNo"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SeqNo].Value = dr["SeqNo"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKID].Value = dr["WKID"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKPriceType].Value = dr["WKPriceType"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKName].Value = DataFunctions.GetFieldValue(dbCon, "rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + dr["WKID"] + "'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.IsKeyWK].Value = dr["IsKeyWK"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKRemark].Value = dr["WKRemark"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CategoryID].Value = dr["CategoryID"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CategoryName].Value = DataFunctions.GetFieldValue(dbCon, "rmCategory", "CategoryName", " CategoryID='" + dr["CategoryID"] + "'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SetID].Value = CvtFunc.ToString(dr["SetID"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SetName].Value = DataFunctions.GetFieldValue(dbCon, "rmSet", "SetName", " SetID='" + dr["SetID"] + "'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.VersionNo].Value = CvtFunc.ToString(dr["VersionNo"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ProductFItemID].Value = CvtFunc.ToString(dr["ProductFItemID"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ProductName].Value = DataFunctions.GetFieldValue(dbCon, "rmProduct", "ProductName", " ProductFItemID='" + dr["ProductFItemID"] + "'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TechnicsName].Value = CvtFunc.ToString(dr["TechnicsName"]);
                //dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ItemNo].Value = CvtFunc.ToString(dr["ItemNo"]);
                //dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ItemName].Value = DataFunctions.GetFieldValue ("iminvmaster","ItemName","ItemNo='"+ CvtFunc.ToString ( dr["ItemNo"]) +"' " );
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.FItemID].Value = CvtFunc.ToString(dr["FItemID"]);
                strSql = "select ItemNo,ItemName from iminvmaster where FItemID='" + CvtFunc.ToString(dr["FItemID"]) + "'";
                DataRow drItemNo = mdbcon.GetDataFirstRow(strSql);
                if (drItemNo == null)
                {

                }
                else
                {
                    dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ItemNo].Value = CvtFunc.ToString(drItemNo["ItemNo"]);
                    dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ItemName].Value = CvtFunc.ToString(drItemNo["ItemName"]);
                }
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKOutName].Value = CvtFunc.ToString(dr["WKOutName"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CalUnit].Value = CvtFunc.ToString(dr["CalUnit"]);
                //dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CutType].Value = CvtFunc.ToString(dr["CutType"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CutType].Value = (CvtFunc.ToString(dr["CutType"]) == "" ? "1" : CvtFunc.ToString(dr["CutType"]));
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.Remark].Value = CvtFunc.ToString(dr["Remark"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardQty].Value = BaseFunctions.FormatNumeric(dr["StandardQty"], "Ns.3");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardWage].Value = CvtFunc.ToString(dr["StandardWage"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardWage26].Value = BaseFunctions.FormatNumeric(dr["StandardWage26"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WorkQty].Value = BaseFunctions.FormatNumeric(dr["WorkQty"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TotalQty].Value = BaseFunctions.FormatNumeric(dr["TotalQty"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.UnitCost].Value = BaseFunctions.FormatNumeric(dr["UnitCost"], "Ns.6");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TotUnitCost].Value = BaseFunctions.FormatNumeric(dr["TotUnitCost"], "Ns.4");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.DtlLaborTotCost].Value = BaseFunctions.FormatNumeric(dr["DetailCost"], "Ns.4");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WorkCost].Value = BaseFunctions.FormatNumeric(dr["WorkCost"], "Ns.4");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TotWorkCost].Value = BaseFunctions.FormatNumeric(dr["DetailTotWorkCost"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.UsedHours].Value = BaseFunctions.FormatNumeric(dr["SpendHours"], "Ns.6");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.RecID].Value = CvtFunc.ToInt(dr["RecID"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ValueChanged].Value = "0";
            }

            if (dgvLabourCost.Rows.Count == 0)
            {
                AddDtlRow(this.dgvLabourCost.Name);
            }
            dbCon.CloseCon();
            base.SetBlankImage(dgvLabourCost);
            m_bCanTrigerCellValueChangedEven_LabourCost = true;
        }

        private void ShowLabourCost()
        {
            InitGridDtlLabourCost();
            FillDtl_LabourCost(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtVersionNo.Text );
        }

        private void dgvBOM_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (dgvBOM.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvBOM.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex, this.dgvBOM.Name);
                }
            }
            else
            {
                if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton && (this.formStatus == FormStatus.Update) && base.HasDelImage(this.dgvBOM, e))
                {
                    this.dgvBOM.CurrentCell.Selected = true;
                    this.dgvBOM.CurrentCell.Selected = false;
                    if (!this.Delete_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    this.dgvBOM.Rows.Remove(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]);
                    if (this.dgvBOM.Rows.Count == 0)
                    {
                        this.AddDtlRow(this.dgvBOM.Name);
                    }
                }
            }
        }

        private void dgvLabourCost_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (dgvLabourCost.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvLabourCost.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex, this.dgvLabourCost.Name);
                }
            }
            else
            {
                if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton && (this.formStatus == FormStatus.Update) && base.HasDelImage(this.dgvLabourCost, e))
                {
                    this.dgvLabourCost.CurrentCell.Selected = true;
                    this.dgvLabourCost.CurrentCell.Selected = false;
                    if (!this.Delete_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    this.dgvLabourCost.Rows.Remove(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]);
                    if (this.dgvLabourCost.Rows.Count == 0)
                    {
                        this.AddDtlRow(this.dgvLabourCost.Name);
                    }
                }
            }
        }
        private void 可更改工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "", strWKName = "",strWKID="", strGridName = "";
            int intCol = 0;

            if (this.tbcMain.SelectedTab == tbpBOM)
                strWKID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value);
            else
                strWKID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value);

            strSQL = " select  A.CategoryName as 类别编号, A.CategoryName as 类别名称,A.WKProductID as 工序编号, A.WKName as 工序名称,A.RecID from rmCategoryWKAlter A inner join rmCategoryWK B on a.hdrseqno=b.seqno where B.CategoryID='" + txtCategoryID.Text + "' and B.WKProductID='" + strWKID + "' ";
            strCaption = "工序选择";


            if (this.tbcMain.SelectedTab == tbpBOM)
                strGridName = this.dgvBOM.Name;
            else
                strGridName = this.dgvLabourCost.Name;

            if (strGridName == this.dgvBOM.Name)
            {
                intCol = this.dgvBOM.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value);
                if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            }
            else
            {
                intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)LabourCostCol.WKName].Value.ToString();
            }
            strFindField = "WkName";
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField, "可更改工序ToolStripMenuItem", strGridName);
        }

        private void 所有工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "", strWKName = "", strGridName = "";
            int intCol = 0;
            strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmWorkingProcedure");
            strSQL = BaseFunctions.GetSqlParts(strSQL, SqlOption.SqlPartMain) + " where GYUsed=1 " + BaseFunctions.GetSqlParts(strSQL, SqlOption.SqlPartOrderBy);
            strCaption = "工序选择";


            if (this.tbcMain.SelectedTab == tbpBOM)
                strGridName = this.dgvBOM.Name;
            else
                strGridName = this.dgvLabourCost.Name;

            if (strGridName == this.dgvBOM.Name)
            {
                intCol = this.dgvBOM.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value);
                if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            }
            else
            {
                intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)LabourCostCol.WKName].Value.ToString();
            }
            strFindField = "WorkingProcedureName";
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField, "所有工序ToolStripMenuItem", strGridName);
        }

        private void 类别工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "", strWKName = "", strGridName = "";
            int intCol = 0;
            strSQL = "select RecID, WKProductID as 工序编号, WKName as 工序名称 from rmCategoryWK where CategoryID='" + txtCategoryID.Text + "' order by WKName";
            strCaption = "类别工序选择";
            strCaption = "工序选择";


            if (this.tbcMain.SelectedTab == tbpBOM)
                strGridName = this.dgvBOM.Name;
            else
                strGridName = this.dgvLabourCost.Name;

            if (strGridName == this.dgvBOM.Name)
            {
                intCol = this.dgvBOM.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value);
                if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            }
            else
            {
                intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)LabourCostCol.WKName].Value.ToString();
            }
            strFindField = "WkName";
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField, "类别工序ToolStripMenuItem", strGridName);
        }

        private void Dtl_LookUp(int iColumnIndex, string strGridName)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "";
            if (strGridName == this.dgvBOM.Name)
            {
                switch ((DtlCol)iColumnIndex)
                {
                    case DtlCol.WKName:

                        cmsWKLookup.Show(this.ActiveControl, new Point(this.ActiveControl.Top, this.ActiveControl.Left));
                        
                        break;
                    case DtlCol.ItemNo:
                        strSQL = BaseFunctions.GetLookUpSQL("iminvmaster");//" select ItemNo,ItemName,SupNo,SupName,MarketCost,CostUnit from iminvmaster where ClosedStatus=0 order by itemno";
                        strCaption = "物料选择";
                        if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value != null) strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value.ToString();
                        strFindField = "ItemNo";
                        break;
                }
            }
            else if (strGridName == this.dgvLabourCost.Name)
            {
                switch ((LabourCostCol)iColumnIndex)
                {
                    case LabourCostCol.WKName:

                        //cmsWKLookup.Show(this.ActiveControl, new Point(this.ActiveControl.Top, this.ActiveControl.Left));
                        //从类别工序标准费用维护中选择                        
                        strSQL = "select RecID,CategoryID as 类别编码,CategoryName as 类别名称,WKProductID as 工序编码,WKName as 工序名称,WKPriceType as 工价类别,WKSalary as 固定工资,WKSTDSalary as 标准工资,WorkCostRate as 工时费用标准,WKSTDQty as 额定产能,STDQtyUnit as 单位 from imCategoryWKWorkCost where WKProductID in ( select WorkingProcedureID from rmWorkingProcedure where FianUsed=1) and CategoryID='" + txtCategoryID.Text + "'";
                        
                        break;
                    case LabourCostCol.CalUnit:
                        strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("imUnit");
                        strCaption = "";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value.ToString();
                        strFindField = "Unit";

                        break;
                    case LabourCostCol.CutType:
                        strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmCutType");
                        strCaption = "分切方式选择";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value.ToString();
                        strFindField = "CutTimes";
                        break;

                    case LabourCostCol.ItemNo:
                        strSQL = BaseFunctions.GetLookUpSQL("iminvmaster"); //" select ItemNo,ItemName,SupNo,SupName,MarketCost,CostUnit from iminvmaster where ClosedStatus=0 order by itemno";
                        strCaption = "物料选择";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value.ToString();
                        strFindField = "ItemNo";
                        break;
                }
            }
            if (strSQL == "") return;
            if (mblnLookUpSortByDescription)
            {
                strSQL = DataFunctions.GetSqlByDescriptionSort(strSQL);
                mblnLookUpSortByDescription = false;
            }

            DtlLookup(iColumnIndex, strSQL, strCaption, strFindValue, strFindField, "", strGridName);
        }

        private void DtlLookup(int iColumnIndex, string strSQL, string strCaption, string strFindValue, string strFindField, string strMenuName, string strGridName)
        {
            frmLookUp frmlookup = null;
            frmLookUpItem frmlookupitem = null;
            bool blnHaveReturnValue = false;
            if ((DtlCol)iColumnIndex == DtlCol.ItemNo)
            {
                frmlookupitem = new frmLookUpItem(strSQL, strCaption, strFindValue, strFindField);
                frmlookupitem.ShowDialog();
                blnHaveReturnValue = frmlookupitem.HaveReturnValue;
            }
            else
            {
                frmlookup = new frmLookUp(strSQL, strCaption, strFindValue, strFindField);
                frmlookup.ShowDialog();
                blnHaveReturnValue = frmlookup.HaveReturnValue;
            }

            if (blnHaveReturnValue)
            {
                if (strGridName == this.dgvBOM.Name)
                {
                    switch ((DtlCol)iColumnIndex)
                    {
                        case DtlCol.WKName:
                            if (strMenuName == this.可更改工序ToolStripMenuItem.Name)
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = frmlookup.GetReturnValue("WkName");
                                //this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            else if (strMenuName == this.类别工序ToolStripMenuItem.Name)
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = frmlookup.GetReturnValue("WKName");
                            }
                            else if (strMenuName == this.所有工序ToolStripMenuItem.Name)
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = frmlookup.GetReturnValue("WorkingProcedureID");
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = frmlookup.GetReturnValue("WorkingProcedureName");
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                           

                            break;
                        case DtlCol.ItemNo:
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value = frmlookupitem.GetReturnValue("FItemID");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value = frmlookupitem.GetReturnValue("ItemNo");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemName].Value = frmlookupitem.GetReturnValue("ItemName");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value = frmlookupitem.GetReturnValue("SupNo");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupName].Value = frmlookupitem.GetReturnValue("SupName");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Price].Value = frmlookupitem.GetReturnValue("MarketCost");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.PriceUnit].Value = frmlookupitem.GetReturnValue("CostUnit");
                            break;
                    }
                }
                else if (strGridName == this.dgvLabourCost.Name)
                {
                    switch ((LabourCostCol)iColumnIndex)
                    {
                        case LabourCostCol.WKName:
                            if (strMenuName == this.可更改工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WkName");
                                //this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            else if (strMenuName == this.类别工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WKName");
                            }
                            else if (strMenuName == this.所有工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WorkingProcedureID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WorkingProcedureName");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            else
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WKName");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKPriceType].Value = frmlookup.GetReturnValue("WKPriceType");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value = frmlookup.GetReturnValue("STDQtyUnit");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value) + "'"); 
                            }

                            break;
                        case LabourCostCol.CalUnit:
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value = frmlookup.GetReturnValue("Unit");
                            break;
                        case LabourCostCol.CutType:
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value = frmlookup.GetReturnValue(strFindField);
                            break;
                        case LabourCostCol.ItemNo:
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = frmlookup.GetReturnValue("FItemID");
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = frmlookup.GetReturnValue("ItemNo");
                            break;
                    }
                }
            }
            if (frmlookupitem != null)
            {
                frmlookupitem.Close();
            }
            else
            {
                frmlookup.Close();
            }
        }


        private void dgvBOM_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvBOM.CurrentRow == null)
            {
                e.Cancel = false;
                return;
            }
            if ( CvtFunc.ToDouble  (dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value.ToString()) > 0 &&  CvtFunc.ToDouble (dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) == 0)
            {
                e.Cancel = false;
                return;

            }

            if (mhtiDtl != null && mhtiDtl.ColumnIndex == (int)DtlCol.DelButton)
            {
                mhtiDtl = null;
                return;
            }


            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                e.Cancel = false;
                return;

            }
            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvBOM") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }

            e.Cancel = !CheckDtlCell(e.ColumnIndex, ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void dgvBOM_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvBOM.CurrentRow != null && int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value.ToString()) > 0 && int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvBOM") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !CheckDtlRow(ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }

        private void dgvBOM_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!m_bCanTrigerCellValueChangedEven || e.ColumnIndex == (int)DtlCol.ValueChanged || e.ColumnIndex ==(int ) DtlCol.DelButton ) return;
            dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ValueChanged].Value = "1";
            m_bDtlChanged = true;
            dgvBOM.EndEdit();
            if (e.ColumnIndex == (int)DtlCol.WKID)
            {
                string strWKID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value);
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKID + "'");
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + strWKID + "'");
            }
            if (e.ColumnIndex == (int)DtlCol.WKName)
            {
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.IsKeyWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsKeyWK", "CategoryID='" + txtCategoryID.Text + "' and WKProductID='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value) + "'");
                if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value) == "")
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureID", "WorkingProcedureName='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "'");
                }
            }
            if (e.ColumnIndex == (int)DtlCol.ItemNo)
            {
                if (DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) + "'") != "")
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value = DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) + "'");
                }
            }
            if (e.ColumnIndex == (int)DtlCol.FItemID)
            {
                string strFItemID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value);
                string strSQL = "select * from iminvmaster where FItemID='" + strFItemID + "'";
                DataRow drItemInfo = mdbcon.GetDataFirstRow(strSQL);
                if (drItemInfo != null)
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value = CvtFunc.ToString(drItemInfo["itemno"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemName].Value = CvtFunc.ToString(drItemInfo["itemname"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value = CvtFunc.ToString(drItemInfo["SupNo"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupName].Value = CvtFunc.ToString(drItemInfo["SupName"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Price].Value = CvtFunc.ToString(drItemInfo["MarketCost"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.PriceUnit].Value = CvtFunc.ToString(drItemInfo["CostUnit"]);
                }
            }
            dgvBOM.EndEdit();
        }

        private void dgvBOM_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvBOM.CurrentCell.Selected = false;
            }
            if (this.dgvBOM.CurrentRow == null) return;
            ShowFormula(this.dgvBOM.CurrentRow.Index);
            ChangeGridSelectRowBackColor(dgvBOM);
        }

        private void ChangeGridSelectRowBackColor(DataGridView dgvView)
        {
            foreach (DataGridViewColumn dccol in dgvView.Columns)
            {
                for (int i = 0; i <= dgvView.Rows.Count - 1; i++)
                {
                    dgvView.Rows[i].Cells[dccol.Name].Style.BackColor = Color.White;
                }
            }
            foreach (DataGridViewColumn dccol in dgvView.Columns)
            {
                dgvView.CurrentRow.Cells[dccol.Name].Style.BackColor = Color.AntiqueWhite;
            }
        }

        private void dgvBOM_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvBOM.CurrentCell.Selected = false;
            }
        }

        private void dgvBOM_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvBOM.EndEdit();

            
            if (e.ColumnIndex == (int)DtlCol.WKName)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.IsKeyWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsKeyWK", "CategoryID='" + txtCategoryID.Text + "' and WKProductID='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value) + "'");
            }
            else if (e.ColumnIndex == (int)DtlCol.ItemNo)
            {
                if (CvtFunc.ToString(this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ItemNo].Value) == "")  // 可能手工删除了物料
                {
                    this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ItemName].Value = "";
                    this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.FItemID].Value = "0";
                    this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.PriceUnit].Value = "";
                }
            }
            else if (e.ColumnIndex == (int)DtlCol.Price)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.3");
            }
            else if (e.ColumnIndex == (int)DtlCol.Qty)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = CvtFunc.ToDouble(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).ToString("F8");               
            }
            else if (e.ColumnIndex == (int)DtlCol.WastageRate)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)DtlCol.LabourCost)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.4");
            }
            else if (e.ColumnIndex == (int)DtlCol.DetailCost)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.4");
            }
            if (dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ValueChanged].Value == "1" && (e.ColumnIndex == (int)DtlCol.Price || e.ColumnIndex == (int)DtlCol.PriceUnit || e.ColumnIndex == (int)DtlCol.ItemNo
                || e.ColumnIndex == (int)DtlCol.Qty || e.ColumnIndex == (int)DtlCol.WastageRate || e.ColumnIndex == (int)DtlCol.LabourCost))
            {
                string strErrMsg = string.Empty;
                if (CheckDtlRow(ref strErrMsg))
                {
                    Update_Detail(this.dgvBOM.Rows[e.RowIndex]);
                }
            }
        }

        private void dgvBOM_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }

        private void dgvBOM_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvBOM, e, (int)DtlCol.DelButton);
            //if (this.formStatus == FormStatus.Query)
            //{
            //    dgvBOM.Enabled = false;
            //    return;
            //}
            string strErrMsg = "";
            if (dgvBOM.CurrentRow != null && CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
            {
                if (CheckDtlRow(ref strErrMsg))
                {
                    if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    //ShowLabourCost();
                }
                else
                {
                    return;
                }
            }
            
        }

        private void dgvBOM_MouseDown(object sender, MouseEventArgs e)
        {

            mhtiDtl = this.dgvBOM.HitTest(e.X, e.Y);

            //System.Windows.Forms.DataGridView.HitTestInfo hti;
            //hti = this.dgvBOM.HitTest(e.X, e.Y);
            //switch (hti.Type)
            //{
            //    case System.Windows.Forms.DataGridViewHitTestType.Cell:
            //        break;
            //}
        }

        private bool dgvBOM_KeyDownEvent(System.Windows.Forms.Keys keyData)
        {
            string strErrMsg = "";
            int j;
            switch (keyData)
            {
                case Keys.Down:
                    #region Key Down

                    this.dgvBOM.EndEdit();
                    if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {

                            if (CheckDtlRow(ref strErrMsg))
                            {

                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvBOM.CurrentCell.RowIndex < dgvBOM.Rows.Count - 1)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                            {
                                return true;
                            }
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }
                    }
                    return true;


                    #endregion
                case Keys.Up:
                    #region Key Up
                    if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvBOM.CurrentCell.RowIndex > 0)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.WKName];
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            if (dgvBOM.CurrentCell.RowIndex > 0)
                            {
                                dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.WKName];
                            }
                        }
                        else if (dgvBOM.Rows.Count > 1)
                        {

                            this.dgvBOM.Rows.Remove(this.dgvBOM.CurrentRow);
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKName];
                        }
                    }
                    return true;
                    #endregion
                case Keys.Enter:
                    #region Key Enter
                    this.dgvBOM.EndEdit();
                    j = BaseFunctions.GetGridViewLastEnabledEditColumn(this.dgvBOM);
                    if (dgvBOM.CurrentCell.ColumnIndex == j)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                        {
                            if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                            {
                                if (CheckDtlRow(ref strErrMsg))
                                {
                                    if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                                }
                                else
                                {
                                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return true;
                                }
                            }
                        }
                        else
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }

                        }
                        if (dgvBOM.CurrentCell.RowIndex < dgvBOM.Rows.Count - 1)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvBOM, dgvBOM.CurrentCell.ColumnIndex);
                        if (j >= 0) SendKeys.Send("{Tab}");
                        //  if (j >= 0) dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex].Cells[j];
                    }

                    return true;
                    #endregion
            }
            return false;
        }

        private void dgvBOM_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            // 对第1列相同单元格进行合并
            if (e.ColumnIndex == (int)DtlCol.WKName && e.RowIndex != -1)
            {
                using
                    (
                    Brush gridBrush = new SolidBrush(this.dgvBOM.GridColor),
                    backColorBrush = new SolidBrush(e.CellStyle.BackColor)
                    )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        // 清除单元格
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                        // 画 Grid 边线（仅画单元格的底边线和右边线）
                        //   如果下一行和当前行的数据不同，则在当前的单元格画一条底边线
                        if (e.RowIndex < dgvBOM.Rows.Count - 1 && dgvBOM.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() != e.Value.ToString())
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                        // 画右边线
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);

                        // 画（填写）单元格内容，相同的内容的单元格只填写第一个
                        if (e.Value != null)
                        {
                            if (e.RowIndex > 0 && dgvBOM.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() == e.Value.ToString())
                            { }
                            else
                            {
                                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 2, e.CellBounds.Y + 5, StringFormat.GenericDefault);
                            }
                        }
                        e.Handled = true;
                    }
                }
            }
        }

        #endregion


        #region LabourCost

        private void dgvLabourCost_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvLabourCost.CurrentRow == null)
            {
                e.Cancel = false;
                return;
            }
            if (int.Parse(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value.ToString()) > 0 && int.Parse(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            if (mhtiDtl != null && mhtiDtl.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                mhtiDtl = null;
                return;
            }


            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                e.Cancel = false;
                return;

            }
            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvLabourCost") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven_LabourCost)
            {
                e.Cancel = false;
                return;
            }

            e.Cancel = !CheckDtlCell_LabourCost(e.ColumnIndex, ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void dgvLabourCost_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvLabourCost.CurrentRow != null && int.Parse(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value.ToString()) > 0 && int.Parse(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvLabourCost") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven_LabourCost)
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !CheckDtlRow_LabourCost(ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void dgvLabourCost_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (formStatus != FormStatus.Update && formStatus != FormStatus.AddNew) return;
            if (!m_bCanTrigerCellValueChangedEven_LabourCost || e.ColumnIndex == (int)LabourCostCol.ValueChanged || e.ColumnIndex ==(int)LabourCostCol.DelButton ) return;
            dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ValueChanged].Value = "1";
            m_bDtlChanged_LabourCost = true;
            dgvLabourCost.EndEdit();
            if (e.ColumnIndex == (int)LabourCostCol.WKID || e.ColumnIndex ==(int)LabourCostCol.WKPriceType)
            {
                string strWKPrineType = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKPriceType].Value);
                string strWKID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKOutName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WKOut", "WorkingProcedureID='" + strWKID + "'");
                string strWKName = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + strWKID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.IsKeyWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsKeyWK", "CategoryID='" + txtCategoryID.Text + "' and WKName='" + strWKID + "'");
                if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) <= 0)
                {
                    double dblWorkCost = DataFunctions.GetCategoryWKWorkCost(txtCategoryID.Text, strWKID,strWKPrineType);
                    if (dblWorkCost > 0)
                    {
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.WorkCost].Value = BaseFunctions.FormatNumeric(dblWorkCost, "Ns.2");
                    }
                }
                string strSQL = "select * from [imCategoryWKWorkCost] where CategoryID='{0}' and WKProductID='{1}' and WKPriceType='{2}'";
                strSQL = string.Format(strSQL, txtCategoryID.Text, strWKID,strWKPrineType);
                DBAccess dbcon = new DBAccess(false, false);
                DataRow drRow = dbcon.GetDataFirstRow(strSQL);
                if (drRow != null)
                {
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.CalUnit].Value = CvtFunc.ToString(drRow["STDQtyUnit"]);
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardQty].Value = BaseFunctions.FormatNumeric(drRow["WKSTDQty"], "Ns.2");
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardWage].Value = BaseFunctions.FormatNumeric(drRow["WKSalary"], "Ns.2");
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardWage26].Value = BaseFunctions.FormatNumeric(drRow["WKSTDSalary"], "Ns.2");
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.UnitCost].Value = BaseFunctions.FormatNumeric(drRow["WKUnitCost"], "Ns.6");                    
                }
                dbcon.CloseCon();
            }
            if (e.ColumnIndex == (int)LabourCostCol.WKName)
            {
                if (CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value) == "")
                {
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureID", "WorkingProcedureName='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value) + "'");
                    string strWKID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value);
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKID + "'");
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKOutName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WKOut", "WorkingProcedureID='" + strWKID + "'");
                }
            }
            else if (e.ColumnIndex == (int)LabourCostCol.CutType)
            {
                string strCutType = CvtFunc.ToString(this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.CutType].Value);
                double dblCutType = CvtFunc.ToDouble(DataFunctions.GetFieldValue("rmCutType", "CutTimes", "CutType='" + strCutType + "'"));
                if (dblCutType == 0)
                {
                    dblCutType = CvtFunc.ToDouble(strCutType);
                }
                double dblWorkQty = CvtFunc.ToDouble(this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.WorkQty].Value);
                if (dblWorkQty != 0)
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.TotalQty].Value = BaseFunctions.FormatNumeric(dblWorkQty / dblCutType, "ns.2");
                else
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.TotalQty].Value = "0";
            }
            else if (e.ColumnIndex == (int)LabourCostCol.ItemNo)
            {
                if (DataFunctions.GetFieldValue("iminvmaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value) + "'") != "")
                {
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value = DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value) + "'");
                }
            }
            if (e.ColumnIndex == (int)LabourCostCol.FItemID)
            {
                string strFItemID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = DataFunctions.GetFieldValue("iminvmaster", "itemno", "FItemID='" + strFItemID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemName].Value = DataFunctions.GetFieldValue("iminvmaster", "itemname", "FItemID='" + strFItemID + "'");
            }
            dgvLabourCost.EndEdit();
        }

        private void dgvLabourCost_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                this.dgvLabourCost.CurrentCell.Selected = false;
            }
            if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value ) > 0)
            {
                this.dgvLabourCost.Columns[(int)LabourCostCol.WKName].ReadOnly = false;
            }
            //else
                //this.dgvLabourCost.Columns[(int)LabourCostCol.WKName].ReadOnly = false;

            ChangeGridSelectRowBackColor(dgvLabourCost);
        }

        private void dgvLabourCost_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                this.dgvLabourCost.CurrentCell.Selected = false;
            }
        }

        private void dgvLabourCost_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvLabourCost.EndEdit();
            if (e.ColumnIndex == (int)LabourCostCol.WorkQty || e.ColumnIndex == (int)LabourCostCol.CutType)
            {
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.TotalQty].Value = BaseFunctions.FormatNumeric(CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value) / CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value), "Ns.2");

            }
            else if (e.ColumnIndex == (int)LabourCostCol.ItemNo)
            {
                if (CvtFunc.ToString(this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ItemNo].Value) == "")
                {
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ItemNo].Value = "";
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ItemName].Value = "";
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.FItemID].Value = "0";
                }
            }
            else if (e.ColumnIndex == (int)LabourCostCol.WorkQty)
            {
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.WKName )
            {
                if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) <= 0)
                {
                    string strWKPriceType = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKPriceType].Value);
                    double dblWorkCost = DataFunctions.GetCategoryWKWorkCost(txtCategoryID.Text, CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value),strWKPriceType);
                    if (dblWorkCost > 0)
                    {
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.WorkCost].Value = BaseFunctions.FormatNumeric(dblWorkCost, "Ns.2");
                    }
                }
            }
            
            if (e.ColumnIndex == (int)LabourCostCol.StandardQty)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardQty].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardQty].Value, "ns.2");
            }
            

            else if (e.ColumnIndex == (int)LabourCostCol.StandardWage)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.StandardWage26)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.TotalQty)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.UsedHours)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.UnitCost)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.8");
            }

            if (CvtFunc.ToString(dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ValueChanged].Value) == "1" && (e.ColumnIndex == (int)LabourCostCol.CalUnit || e.ColumnIndex == (int)LabourCostCol.CutType || e.ColumnIndex == (int)LabourCostCol.StandardQty
                || e.ColumnIndex == (int)LabourCostCol.UsedHours || e.ColumnIndex == (int)LabourCostCol.UnitCost || e.ColumnIndex == (int)LabourCostCol.WorkCost
                || e.ColumnIndex == (int)LabourCostCol.TotalQty || e.ColumnIndex == (int)LabourCostCol.WorkQty || e.ColumnIndex == (int)LabourCostCol.WKName))
            {
                string strErrMsg = string.Empty;
                if (CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    Update_Detail_LabourCost(this.dgvLabourCost.Rows[e.RowIndex]);
                }
            }
        }

        private void dgvLabourCost_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }

        private void dgvLabourCost_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvLabourCost, e, (int)LabourCostCol.DelButton);
            //if (this.formStatus == FormStatus.Query)
            //{
            //    dgvLabourCost.Enabled = false;
            //    return;
            //}
            string strErrMsg = "";
            if (dgvLabourCost.CurrentRow != null && CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
            {
                if (CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    if (!Update_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }

        }

        private void dgvLabourCost_MouseDown(object sender, MouseEventArgs e)
        {

            mhtiDtl = this.dgvLabourCost.HitTest(e.X, e.Y);

            //System.Windows.Forms.DataGridView.HitTestInfo hti;
            //hti = this.dgvLabourCost.HitTest(e.X, e.Y);
            //switch (hti.Type)
            //{
            //    case System.Windows.Forms.DataGridViewHitTestType.Cell:
            //        break;
            //}
        }

        private bool dgvLabourCost_KeyDownEvent(System.Windows.Forms.Keys keyData)
        {
            string strErrMsg = "";
            int j;
            switch (keyData)
            {
                case Keys.Down:
                    #region Key Down

                    this.dgvLabourCost.EndEdit();
                    if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                        {

                            if (CheckDtlRow_LabourCost(ref strErrMsg))
                            {

                                if (!Update_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvLabourCost.CurrentCell.RowIndex < dgvLabourCost.Rows.Count - 1)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex + 1].Cells[(int)LabourCostCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                    }
                    else
                    {
                        if (CheckDtlRow_LabourCost(ref strErrMsg))
                        {
                            if (!Update_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                            {
                                return true;
                            }
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }
                    }
                    return true;


                    #endregion
                case Keys.Up:
                    #region Key Up
                    if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                        {
                            if (CheckDtlRow_LabourCost(ref strErrMsg))
                            {
                                if (!Update_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvLabourCost.CurrentCell.RowIndex > 0)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex - 1].Cells[(int)LabourCostCol.WKName];
                        }
                    }
                    else
                    {
                        if (CheckDtlRow_LabourCost(ref strErrMsg))
                        {
                            if (!Update_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            if (dgvLabourCost.CurrentCell.RowIndex > 0)
                            {
                                dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex - 1].Cells[(int)LabourCostCol.WKName];
                            }
                        }
                        else if (dgvLabourCost.Rows.Count > 1)
                        {

                            this.dgvLabourCost.Rows.Remove(this.dgvLabourCost.CurrentRow);
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKName];
                        }
                    }
                    return true;
                    #endregion
                case Keys.Enter:
                    #region Key Enter
                    this.dgvLabourCost.EndEdit();
                    j = BaseFunctions.GetGridViewLastEnabledEditColumn(this.dgvLabourCost);
                    if (dgvLabourCost.CurrentCell.ColumnIndex == j)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                        {
                            if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                            {
                                if (CheckDtlRow_LabourCost(ref strErrMsg))
                                {
                                    if (!Update_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                                }
                                else
                                {
                                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return true;
                                }
                            }
                        }
                        else
                        {
                            if (CheckDtlRow_LabourCost(ref strErrMsg))
                            {
                                if (!Update_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }

                        }
                        if (dgvLabourCost.CurrentCell.RowIndex < dgvLabourCost.Rows.Count - 1)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex + 1].Cells[(int)LabourCostCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvLabourCost, dgvLabourCost.CurrentCell.ColumnIndex);
                        if (j >= 0) SendKeys.Send("{Tab}");
                        //  if (j >= 0) dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex].Cells[j];
                    }

                    return true;
                    #endregion
            }
            return false;
        }



        private void dgvLabourCost_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            // 对第1列相同单元格进行合并
            if (e.ColumnIndex == (int)LabourCostCol.WKName    && e.RowIndex != -1)
            {
                using
                    (
                    Brush gridBrush = new SolidBrush(this.dgvLabourCost.GridColor),
                    backColorBrush = new SolidBrush(e.CellStyle.BackColor)
                    )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        // 清除单元格
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                        // 画 Grid 边线（仅画单元格的底边线和右边线）
                        //   如果下一行和当前行的数据不同，则在当前的单元格画一条底边线
                        if (e.RowIndex < dgvLabourCost.Rows.Count - 1 && dgvLabourCost.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() != e.Value.ToString())
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                        // 画右边线
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);

                        // 画（填写）单元格内容，相同的内容的单元格只填写第一个
                        if (e.Value != null)
                        {
                            if (e.RowIndex > 0 && dgvLabourCost.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() == e.Value.ToString())
                            { }
                            else
                            {
                                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 2, e.CellBounds.Y + 5, StringFormat.GenericDefault);
                            }
                        }
                        e.Handled = true;
                    }
                }
            }
        }


        #endregion
        private void FillTree()
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strSQL = "select TypeId,TypeName,RecID from RMProductFirstType order by TypeId";
            DataTable dtItem = dbcon.GetDataTable(strSQL);
            foreach (DataRow drType in dtItem.Rows)
            {
                TreeNode tvNode = new TreeNode(CvtFunc.ToString(drType["TypeId"]) + "-" + CvtFunc.ToString(drType["TypeName"]));
                this.tvTree.Nodes.Add(tvNode);
                int intRow = 0;
                strSQL = "select TypeId,TypeName from RMProductSecondType where parentid='" + CvtFunc.ToString(drType["RecID"]) + "'";
                DataTable dtDtl = dbcon.GetDataTable(strSQL);
                foreach (DataRow drDtl in dtDtl.Rows)
                {
                    tvNode.Nodes.Add(CvtFunc.ToString(drDtl["TypeId"]) + "-" + CvtFunc.ToString(drDtl["TypeName"]));
                }
            }
            dbcon.CloseCon();
        }
        private void ShowFormula( int intRow )
        {
            if ( this.dgvBOM.Rows[intRow]==null ) return ;
            string strRecID= CvtFunc.ToString ( this.dgvBOM.Rows[intRow].Cells[(int)DtlCol.RecID].Value) ;
            if ( CvtFunc.ToDouble  ( strRecID  )<=0)
            {
                txtCalFormula.Text ="";
                return ;
            }
            if (mTypePara == MtnType.isRev)
            {
                txtCalFormula.Text = DataFunctions.GetFieldValue(mdbcon, "rmWKProductFormulaRev", "WKFormula", "BOMRecID='" + strRecID + "'");
            }
            else
            {
                txtCalFormula.Text = DataFunctions.GetFieldValue(mdbcon, "rmWKProductFormulaSales", "WKFormula", "BOMRecID='" + strRecID + "'");
            }
        }

        private void btnTallyCalculate_Click(object sender, EventArgs e)
        {
            string strSQL = string.Empty;
            if (this.tbcMain.SelectedTab == tbpBOM)
            {
                if (!this.Update_Detail(dgvBOM.CurrentRow)) return;
                if (this.dgvBOM.CurrentRow == null) return;
                if (this.dgvBOM.CurrentCell == null) return;
                if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) == "") return;
                string strRecID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value);
                frmRMWKFormula frmCal = new frmRMWKFormula(strRecID, mTypePara== MtnType.isRev ? frmRMWKFormula.FormulaType.FromProductBOMRev : frmRMWKFormula.FormulaType.FromProductBOMSales);
                frmCal.StartPosition = FormStartPosition.CenterParent;
                string strCaption = "定额数量  计算公式选择： " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "    " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) + "  " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemName].Value);
                frmCal.Text = strCaption;
                frmCal.ShowDialog();
                strSQL = "select * from "+ ( mTypePara== MtnType.isRev ? "rmProductBOMDetailRev":"rmProductBOMDetailSales") +" where RecID='" + strRecID + "'";

            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                if (this.dgvLabourCost.CurrentRow == null) return;
                if (this.dgvLabourCost.CurrentCell == null) return;
                this.dgvLabourCost.EndEdit();
                if (!this.Update_Detail_LabourCost(dgvLabourCost.CurrentRow)) return;
                string strRecID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value);
                frmRMWKFormula frmCal = new frmRMWKFormula(strRecID, mTypePara== MtnType.isRev ? frmRMWKFormula.FormulaType.OtherProductBOMRev : frmRMWKFormula.FormulaType.OtherProductBOMSales);
                frmCal.StartPosition = FormStartPosition.CenterParent;
                frmCal.Text = "项目分摊  计算公式选择： " + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value) + "    " + txtProductName.Text;
                frmCal.ShowDialog();
                strSQL = "select * from "+ ( mTypePara== MtnType.isRev ? "rmProductBOMLabourCostRev":"rmProductBOMLabourCostSales") +" where RecID='" + strRecID + "'";

            }

            if (this.tbcMain.SelectedTab == tbpBOM)
            {
                DataRow drRow = mdbcon.GetDataFirstRow(strSQL);
                RMProductBOMRevDAL rmDAL = new RMProductBOMRevDAL();
                rmDAL.UpdateBOMDetail(mdbcon, drRow);

                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Qty].Value = drRow["Qty"];
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.TotalCost].Value = drRow["TotalCost"];
                this.dgvBOM.EndEdit();
                this.dgvBOM.RefreshEdit();
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                DataRow drRow = mdbcon.GetDataFirstRow(strSQL);
                RMProductBOMRevDAL rmDAL = new RMProductBOMRevDAL();
                rmDAL.UpdateLabourCostDetail(mdbcon, drRow);
                if (drRow != null)
                {
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value = drRow["WorkQty"];
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.TotalQty].Value = drRow["TotalQty"];
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.TotWorkCost].Value = drRow["DetailTotWorkCost"];
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.UsedHours].Value = drRow["SpendHours"];
                    this.dgvLabourCost.EndEdit();
                    this.dgvLabourCost.RefreshEdit();
                }
            }
            FillHdrData(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtVersionNo.Text,txtTechnicsName .Text );
            ShowFormula(this.dgvBOM.CurrentRow.Index);
            this.TimeStamp = (byte[])mdbcon.GetObjectValue("Select RecStamp From " + this.TableName + " Where Recid=" + m_lRecId);
        }

        private void btnCondition_Click(object sender, EventArgs e)
        {
            frmRMProductBOMRevSetting frmSetting = new frmRMProductBOMRevSetting(mTypePara.ToString () );
            string strCond = frmSetting.GetCondition();
            if (strCond == "")
            {
                ShowOverViewGrid(); 
            }
            else
            {
                ShowOverViewGrid(strCond);
            }
        }

        private void btnCopyToNewVer_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew) return; 
            
            DBAccess dbcon = new DBAccess(false, false);
            try
            {
                
                dbcon.BeginTran();
                Cursor.Current = Cursors.WaitCursor;
                string strRecID = CvtFunc.ToString ( this.dgList.CurrentRow.Cells["RecID"].Value);
                DataRow drHdr = dbcon.GetDataFirstRow("select * from " + (mTypePara == MtnType.isRev ? "rmProductBOMRev" : "rmProductBOMSales")+" where RecID='" + strRecID + "'");
                if (mTypePara == MtnType.isRev)
                {
                    RMProductBOMRevDAL rmDAL = new RMProductBOMRevDAL();
                    if (rmDAL.CopytoNewVer(dbcon, drHdr))
                    {
                        dbcon.CommitTran();
                    }
                    else
                    {
                        dbcon.RollbackTran();
                    }
                }
                else
                {
                    RMProductBOMSalesDAL rmDAL = new RMProductBOMSalesDAL();
                    if (rmDAL.CopytoNewVer(dbcon, drHdr))
                    {
                        dbcon.CommitTran();
                    }
                    else
                    {
                        dbcon.RollbackTran();
                    }
                }
                Cursor.Current = Cursors.Default;
                this.dgList.RefreshData();
                this.dgList.Focus();
                string strNewVisionNo = "";
                if (mTypePara == MtnType.isRev)
                {
                    strNewVisionNo = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue(dbcon, "rmProductBOMRev", "max(VersionNo)", "ProductFItemID='" + drHdr["ProductFItemID"]  + "'")));
                }
                else
                {
                    strNewVisionNo = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue(dbcon, "rmProductBOMSales", "max(VersionNo)", "ProductFItemID='" + drHdr["ProductFItemID"] + "'")));
                }
                MessageBox.Show("复制成功完成！新的版本号是： " + strNewVisionNo + "", "PDM", MessageBoxButtons.OK, MessageBoxIcon.Information);
              
            }
            catch (Exception ex)
            {
                dbcon.RollbackTran();
                return;
            }
           
            dbcon.CloseCon();
            
        }

        private void txtCalFormula_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnCopyBOMToLabour_Click(object sender, EventArgs e)
        {
            frmRMCopyBOMToLabourCost frmLabourCost = new frmRMCopyBOMToLabourCost();
            frmRMCopyBOMToLabourCost.Parameter para = new frmRMCopyBOMToLabourCost.Parameter();
            para.strCategoryName = txtCategoryName.Text;
            para.strSetName = txtSetName.Text;
            para.strVerNo = txtVersionNo.Text;
            para.strProductName = txtProductName.Text;

            para.strCategoryID = txtCategoryID.Text;
            para.strSetID = txtSetID.Text;            
            para.strProductFitemID = txtProductFItemID.Text;

            if (mTypePara == MtnType.isRev)
            {
                frmLabourCost.ShowFrom(frmRMCopyBOMToLabourCost.FromType.BOMRev, this.dgvBOM, para);
            }
            else
            {
                frmLabourCost.ShowFrom(frmRMCopyBOMToLabourCost.FromType.BOMSales, this.dgvBOM, para);
            }
            
            if (frmLabourCost.mblnHasReturn)
            {
                foreach (DataGridViewRow dgvRow in frmLabourCost.dgvBOM.Rows)
                {
                    if (CvtFunc.ToBoolean(dgvRow.Cells["SEL"].Value))
                    {
                        string strWKID = CvtFunc.ToString(dgvRow.Cells["WKID"].Value);
                        string strItemFItemID = CvtFunc.ToString(dgvRow.Cells["FItemID"].Value);
                        int intInsertRow = GetLastRowInGridForSpecilaWKName(strWKID);
                        string strErrMsg = "";
                        if (CheckDtlRow_LabourCost(ref strErrMsg))
                        {
                            AddDtlRow(this.dgvLabourCost.Name, intInsertRow);
                        }
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = strWKID;
                        this.dgvLabourCost_CellValueChanged(this.dgvLabourCost, new DataGridViewCellEventArgs((int)LabourCostCol.WKName, this.dgvLabourCost.CurrentCell.RowIndex));
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = DataFunctions.GetFieldValue("iminvmaster", "itemno", "FItemID='" + strItemFItemID + "'");
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemName].Value = DataFunctions.GetFieldValue("iminvmaster", "itemname", "FItemID='" + strItemFItemID + "'");
                        this.Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow);
                    }
                }
            }
        }


        private int GetLastRowInGridForSpecilaWKName(string strWKID)
        {
            bool blnFind = false;
            foreach (DataGridViewRow dgvRow in this.dgvLabourCost.Rows)
            {
                if (CvtFunc.ToString(dgvRow.Cells["WKID"].Value) == strWKID)
                {
                    blnFind = true;
                }
                else
                {
                    if (blnFind) return dgvRow.Index;
                }
            }
            return this.dgvLabourCost.Rows.Count - 1;

        }

        private void ubtWKCost_Click(object sender, EventArgs e)
        {
            frmRMWKWorkCostLookup frmLookup = new frmRMWKWorkCostLookup();
            frmLookup.ShowWorkCost(mdbcon, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtVersionNo.Text, CvtFunc.ToDouble(txtTotalWorkCostRev.Text));
        }

        private void tvTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Nodes.Count == 0) //最后一层
            {
                string strMaterialID = "";
                strMaterialID = CvtFunc.ToString(e.Node.Text.ToString()).Split('-')[0];
                //this.dgList.FindRecord(strMaterialID, "MaterialTypeID");
                string strCond = "where ProductID like '" + strMaterialID + "%'";
                ShowOverViewGrid(strCond);
            }
            else  //最上层
            {
                string strMaterialID = "";
                strMaterialID = CvtFunc.ToString(e.Node.Text.ToString()).Split('-')[0];
                //this.dgList.FindRecord(strMaterialID, "MaterialTypeID");
                string strCond = "where ProductID like '" + strMaterialID + "%'";
                ShowOverViewGrid(strCond);
            }
        }       

    }
}
